Topic description:
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
'/'
together, such as"/home//foo/"
.
In this case, you should ignore redundant slashes and return"/home/foo"
.
Problem solving ideas:
There are three special cases for this question: multiple '/' characters, "../" strings, and "./" strings. Therefore, when traversing, I skip '/' to add other arrays, and then compare the obtained sub-arrays with ".." and ".", and clear the obtained string each time.
Code:
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 // Add case 9 triggered by '/' if (temp.empty()) 10 // temp is an empty string 11 continue ; 12 if(temp == " . " ) { 13 // temp is '.' 14 temp. clear(); 15 continue ; 16 } 17 if (temp == " .. " ) { 18 // temp is ".." 19 int next = ret.rfind( " / " ); 20 if (next > 0 ) 21 // Prevent ret from being an empty string and next is -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 // Because '/' is used as the addition condition, the last character may not be '/', so we need to compare again 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 };