71. Simplify Path 解题记录
Posted 宵夜
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了71. Simplify Path 解题记录相关的知识,希望对你有一定的参考价值。
题目描述:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
Corner Cases:
- Did you consider the case where path =
"/../"
?
In this case, you should return"/"
. - Another corner case is the path might contain multiple slashes
‘/‘
together, such as"/home//foo/"
.
In this case, you should ignore redundant slashes and return"/home/foo"
.
解题思路:
这题的特殊情况有三个:多个‘/‘字符,"../"字符串和"./"字符串。因此我在遍历的时候直接略过‘/‘添加其他数组,再将得到的子数组与".."和"."比较,每次比较清空得到的字符串。
代码:
1 class Solution { 2 public: 3 string simplifyPath(string path) { 4 string ret, temp; 5 int n = path.length(); 6 for (int i = 0; i < n; i++) { 7 if (path[i] == ‘/‘) { 8 //以‘/‘为触发添加情况 9 if (temp.empty()) 10 //temp为空串 11 continue; 12 if (temp == ".") { 13 //temp为‘.‘ 14 temp.clear(); 15 continue; 16 } 17 if (temp == "..") { 18 //temp为".." 19 int next = ret.rfind("/"); 20 if (next > 0) 21 //防止ret为空串,next为-1的情况 22 ret.erase(ret.begin() + next, ret.end()); 23 else 24 ret.clear(); 25 temp.clear(); 26 } 27 else { 28 //添加 29 ret = ret + ‘/‘ + temp; 30 temp.clear(); 31 } 32 } 33 else 34 temp += path[i]; 35 } 36 if (temp == ".." && ret.length()>1) { 37 //因为以‘/‘为添加条件,可能会碰到最后一个字符不是‘/‘的情况,所以最后要再比较一次 38 ret.erase(ret.begin() + ret.rfind("/"), ret.end()); 39 } 40 if (temp != "." && temp != ".." && !temp.empty()) 41 ret = ret + ‘/‘ + temp; 42 if (ret.empty()) 43 ret = "/"; 44 return ret; 45 } 46 };
以上是关于71. Simplify Path 解题记录的主要内容,如果未能解决你的问题,请参考以下文章