Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
"/../"
?"/"
.‘/‘
together,
such as "/home//foo/"
."/home/foo"
.解题思路:
化简路径。可以用一个栈来记录。遍历原路径,遇到/,则判断最近一个单词。若为"."则什么也不做。若"..",弹出栈顶元素,否则入栈。
有一个比较巧的办法是,直接在path后面添加一个斜杠,这样就能避免讨论后面有斜杠还是没有斜杠了。
class Solution { public: string simplifyPath(string path) { stack<string> ss; path = path + "/"; int len = path.length(); string s=""; for(int i=0; i<len; i++){ if(path[i]=='/'){ if(s==".."){ if(!ss.empty()){ ss.pop(); } }else if(s!=""&&s!="."){ ss.push(s); } s=""; }else{ s=s+path[i]; } } while(!ss.empty()){ s = string("/") + ss.top() + s; ss.pop(); } if(s==""){ s="/"; } return s; } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/kangrydotnet/article/details/47105813