71. Simplify Path 解題記錄
阿新 • • 發佈:2018-04-15
tro contain this sla 特殊情況 思路 strong sim 一次
題目描述:
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
‘/‘
"/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 解題記錄