stringsimplifyPath(string path){ int len = path.length(); if (len <= 1)return"/"; stack<string> s; string str = ""; int i = 1; while (i < len) { while (i < len&&path[i] == '/')i++; if (i<len&&path[i] == '.') { if (i + 1 < len&&path[i + 1] == '.') { if (i+2==len||i + 2<len&&path[i + 2] == '/') { if (!s.empty())s.pop(); i += 3; } elseif (i + 2<len) { while (i < len&&path[i] != '/') { str = str + path[i]; i++; } s.push(str); str = ""; } } elseif (i + 1 == len || i + 1 < len&&path[i + 1] == '/') i += 2; else { while (i < len&&path[i] != '/') { str = str + path[i]; i++; } s.push(str); str = ""; } } else { while (i < len&&path[i] != '/') { str = str + path[i]; i++; } if (str.length() > 0) s.push(str); str = ""; } } string res = ""; while (!s.empty()) { string t = s.top(); res = '/' + t + res; s.pop(); } if (!res.length()) return"/"; return res; }
其实应该是可以在原来的字符串上直接修改的。
while语句总是忘了写递增条件,这是什么坏毛病。
…居然是文件名??太过分了,测试如下:
1 2 3 4 5 6 7
[root@iZm5efgntvp9yn8px32ud1Z ~]# cd ... -bash: cd: ...: No such file or directory [root@iZm5efgntvp9yn8px32ud1Z ~]# cd .... -bash: cd: ....: No such file or directory [root@iZm5efgntvp9yn8px32ud1Z ~]# cd .. [root@iZm5efgntvp9yn8px32ud1Z /]# cd . [root@iZm5efgntvp9yn8px32ud1Z /]#