考察的知识点:字符串;
解答方法分析:
- 使用栈来辅助简化路径。遍历路径中的每个区域名,当遇到区域名为"."时,表示当前目录本身,不做任何操作;当遇到区域名为".."时,表示切换到上一级目录,需要将栈顶元素出栈;其他情况下,表示普通区域名,入栈。
- 将栈中剩余的区域名按照路径规范拼接起来,得到简化后的路径。
所用编程语言:C++;
完整编程代码:↓
class Solution { public: string find_dangerous_cow_path(string path) { stack<string> stk; int n = path.size(); for (int i = 0; i < n; ) { while (i < n && path[i] == '/') { ++i; } string region; while (i < n && path[i] != '/') { region += path[i++]; } if (region == ".") { } else if (region == "..") { if (!stk.empty()) { stk.pop(); } } else { stk.push(region); } } string simplifiedPath; while (!stk.empty()) { if (simplifiedPath.empty()) { simplifiedPath = stk.top(); } else { simplifiedPath = stk.top() + "/" + simplifiedPath; } stk.pop(); } if (simplifiedPath.empty()) { simplifiedPath = "/"; } return "/" + simplifiedPath; } };