leetcode 79:simplify path
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
本題簡(jiǎn)單來(lái)說(shuō) 就是字符串的處理 同時(shí)要有相關(guān)的情況分類(lèi) 比如當(dāng)前目錄 父目錄 多個(gè)斜線等
但其實(shí) 就父目錄時(shí)需要回到上一路經(jīng) 當(dāng)前目錄時(shí)不做任何變化 其他目錄時(shí)需要進(jìn)入其他目錄 這一特征? 本題可用棧來(lái)存儲(chǔ)整個(gè)路徑尋找的過(guò)程
在path中 逐一找到斜線之間的當(dāng)前路徑名 并分類(lèi)判斷 分類(lèi)處理? 使得棧中存儲(chǔ)的為路徑的一系列名字? 最后再反向串起來(lái)成路徑真正的字符串即可。
class Solution {
public:
??? string simplifyPath(string path) {
??????? string res_path="";
??????? if (path.size()==0)
??????????? return res_path;
??????? stack<string> stack_path;
??????? for (int i=0; i<path.size();)
??????? {
??????????? while(i<path.size() && path[i]=='/')
??????????????? ++i;
??????????? string name="";
??????????? while(i<path.size() && path[i]!='/')
??????????????? name += path[i++];
??????????? if (name==".." && !stack_path.empty())
??????????????? stack_path.pop();
??????????? else if(name!="" && name!="." && name!="..")
??????????????? stack_path.push(name);
??????? }
??????? if (stack_path.empty())
??????????? res_path += '/';
??????? else
??????? {
??????????? while(!stack_path.empty())
??????????? {
??????????????? res_path = '/'+stack_path.top()+res_path;
??????????????? stack_path.pop();
??????????? }
??????? }
??????? return res_path;
??? }
};
轉(zhuǎn)載于:https://www.cnblogs.com/weiyi-mgh/p/6406363.html
總結(jié)
以上是生活随笔為你收集整理的leetcode 79:simplify path的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: onchange onpropertyc
- 下一篇: jQuery给动态添加的元素绑定事件的方