71. Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
path = "/a/../../b/../c//.//"
, => "/c"
path = "/a//b////c/d//././/.."
, => "/a/b/c"
In a UNIX-style file system, a period ('.') refers to the current directory, so it can be ignored in a simplified path. Additionally, a double period ("..") moves up a directory, so it cancels out whatever the last directory was. For more information, look here: https://en.wikipedia.org/wiki/Path_(computing)#Unix_style
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"
.
思路:
利用stack
如果是.. 返回上一层目录----》弹栈
如果是. 或者空字符 啥也不操作
如果是字母:进入字母目录---》》 把字母压栈
1 class Solution { 2 public: 3 string simplifyPath(string path) { 4 string res,temp; 5 stack<string> mystack ; 6 stringstream ss(path); 7 while(getline(ss,temp,'/')){ 8 if(temp==".."){ 9 if(mystack.size()!=0) 10 mystack.pop(); 11 } 12 else if(temp=="."||temp=="") 13 continue; 14 else 15 mystack.push(temp); 16 17 } 18 while (!mystack.empty()){ 19 res="/"+mystack.top()+res; 20 mystack.pop(); 21 } 22 23 return res.empty() ? "/" : res; 24 25 } 26 27 };