LeetCode 71. Simplify Path 求絕對路徑,字串處理題
阿新 • • 發佈:2019-02-02
字串 處理題
注意以下幾點即可:
//// 即連續的/
/... 則...是目錄名或檔名,而非..和.
空的輸入,為/
class Solution { public: string simplifyPath(string path) { vector<string> spath; string sdir; int i, j = 1; while(j < path.size()){ i = path.find('/',j); if(i == -1) i = path.size(); sdir = path.substr(j, i-j); if(sdir == ".."){ if(!spath.empty()) spath.pop_back(); } else if(sdir != "." && sdir != "") spath.push_back(sdir); j = i+1; } string ans; for(i = 0;i < spath.size(); i++){ ans += "/"; ans += spath[i]; } if(ans.size()==0) ans += "/"; return ans; } };