Simplify Path
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"
.
思路:利用栈来对字符串进行处理。str是保存"/"和"/"间的的字符串。有以下一些情形:
1)当path[i]=="/"时,然后对str进行处理a)str==".."时看栈是否为空,去除栈顶元素(b)str!="."&&str!="",则入栈(c)其他情况,str="";
2)当path[i]!="/"时,path[i]加入到str中去。
注意:有可能最后一个字符串不是以"/"结束,所以这一部分还得按照1)步骤来处理。
class Solution { public: string simplifyPath(string path) { stack<string> s; string str; int n=path.size(); for(int i=0;i<n;i++) { if(path[i]=='/') { if(str=="..") { if(!s.empty()) s.pop(); } else if(str!="."&&str!="") s.push(str); str=""; } else { str+=path[i]; } } /*处理最后字符不是以"/"结束,但是str保存了一部分字符串*/ if(str=="..") { if(!s.empty()) s.pop(); } else if(str!="."&&str!="") s.push(str); if(s.empty()) return "/"; string result; while(!s.empty()) { result="/"+s.top()+result; s.pop(); } return result; } };