標籤:top stream col continue size amp 多個 empty class
給定一個文檔 (Unix-style) 的完全路徑,請進行路徑簡化。
例如,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
邊界情況:
- 你是否考慮了 路徑 =
"/../" 的情況?
- 在這種情況下,你需返回
"/" 。
- 此外,路徑中也可能包含多個斜杠
‘/‘ ,如 "/home//foo/" 。
在這種情況下,你可忽略多餘的斜杠,返回 "/home/foo" 。
首先應該明確,"."和".."都是目錄。因此,適合將/作為分隔字元,將目錄全部分開。為了方便,總是使得路徑最後一個字元為‘/‘。如果是這樣做的話,需要注意棧為空白的情況。
class Solution {public: string simplifyPath(string path) { stack<string> s; if(path.size() > 1 && path.back() != ‘/‘) { path.push_back(‘/‘); } for(int i = 0; i < path.size(); ) { while(i < path.size() && path[i] == ‘/‘) { i++; } int j = i + 1; while(j < path.size() && path[j] != ‘/‘) { j++; } //[i, j),j是第一個/ string cur = path.substr(i, j - i); if(cur == "..") { if(!s.empty()) { s.pop(); } } else if(cur == "") { break; } else if(cur != ".") { s.push(cur); } i = j; } string res; while(!s.empty()) { res.insert(0, "/" + s.top()); s.pop(); } return res == ""? "/": res; }};
另一種使用getline的方法更清晰:
class Solution {public: string simplifyPath(string path) { string res, tmp; vector<string> stk; stringstream ss(path); while(getline(ss,tmp,‘/‘)) { // 用/作為分隔字元(預設是分行符號,第三個參數為自訂的分隔字元) if (tmp == "" || tmp == ".") continue; if (tmp == ".." && !stk.empty()) stk.pop_back(); else if (tmp != "..") stk.push_back(tmp); } for(auto str : stk) res += "/"+str; return res.empty() ? "/" : res; }};
LeetCode 71. 簡化路徑