用个stack来记录目录,如果要往前跳就pop就好了
不过要主意的是
...
.xxx
..xxx
这样的在unix是合法路径,开始没考虑TAT,以至于后面改的代码很乱,虽然AC了...
class Solution { public: string simplifyPath(string path) { int size = path.size(); if(size == 0) return ""; int i = 0; stack<string> st; bool x = false; while(i < size){ if(path[i] == '/'){ while(i < size && path[i] == '/') i++; x = true; continue; } if(path[i] == '.'){ if (i + 1 < size && path[i+1] == '.'){ if(i+2 < size && path[i+2] != '/'){ int start = i; while(i < size && path[i] != '/') i++; if(x) st.push(path.substr(start , i - start)); x = false; continue; } if(!st.empty())st.pop(); i++;i++; }else{ if(i+1 < size && path[i+1] != '/'){ int start = i; while(i < size && path[i] != '/') i++; if(x) st.push(path.substr(start , i - start)); x = false; continue; } i++; } x = false; continue; } int start = i; while(i < size && path[i] != '/' ){ i++; } if(x) st.push(path.substr(start , i - start)); x = false; } stack<string> ans; while(!st.empty()){ ans.push(st.top()); st.pop(); } if(ans.empty()) return "/"; string final = ""; while(!ans.empty()){ final += "/" + ans.top(); ans.pop(); } return final; } };
-------update June 22, 2014------
class Solution { public: string simplifyPath(string path) { stack<string> dic; int size = path.size(); int p = 0; while(p < size) { while(p < size && path[p] == '/') p++; int start = p; while(p < size && path[p] != '/') { p++; } if(p == start) break; string tmp = path.substr(start , p-start); if(tmp == ".") continue; if(tmp == "..") { if(dic.size() > 0) dic.pop(); continue; } dic.push(tmp); } string ans = ""; stack<string> rev; while(dic.size() > 0) { rev.push(dic.top()); dic.pop(); } while(rev.size() > 0) { ans += ("/" + rev.top()); rev.pop(); } if(ans == "") ans = "/"; return ans; } };
不知为啥之前的写那么复杂
by 1957