2026企业知识库管理系统选型指南:主流产品与实战避坑
2026/9/11 10:18:32
思路:按/分割路径,用一个栈存放目录名:
.:跳过..:栈非空则弹栈最后用/拼接。
implSolution{pubfnsimplify_path(path:String)->String{letmutstack:Vec<&str>=Vec::new();forpartinpath.split('/'){matchpart{""|"."=>{}".."=>{stack.pop();}dir=>stack.push(dir),}}letmutresult=String::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"