Kimi LeetCode 71. 简化路径 Rust实现
发布时间:2026/9/11 9:36:14 作者:尧图编辑部 阅读量:1,286

LeetCode 71. 简化路径思路:按/分割路径,用一个栈存放目录名:遇到空串或.:跳过遇到..:栈非空则弹栈其他:入栈最后用/拼接。implSolution{pubfnsimplify_path(path:String)-String{letmutstack:VecstrVec::new();forpartinpath.split(/){matchpart{|.{}..{stack.pop();}dirstack.push(dir),}}letmutresultString::new();fordirinstack{result.push(/);result.push_str(dir);}ifresult.is_empty(){/.to_string()}else{result}}}要点说明:split(/)天然处理了多个连续斜杠,空串直接跳过..时要判断栈非空再pop(已在根目录时..无效果)答案一定以/开头,栈空时返回/复杂度:时间 O(n),空间 O(n)。例如输入/home//foo/../bar:home入栈,空串跳过,foo入栈,..弹掉foo,bar入栈结果为/home/bar