码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode Simplify Path

时间:2014-07-16 17:54:16      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   strong   art   for   

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".

题目不难,主要考虑一些特殊情况。

对于path = "/a/./b/../../c/", => "/c",模拟一下

先按照‘/‘对字符串进行分割,得到 [a, . , b, .. , .. , c]

首先进入目录a,注意 ‘.‘ 代表当前目录 ,".."代表上一个目录

然后到达‘.‘,还是在当前目录,/a

然后到达‘b‘,这为/a/b

然后到达‘..‘,这是回到父目录,则变为/a

然后到达‘..‘,继续回到父目录,则变为/

然后到达‘c‘,则达到子目录,变为/c

class Solution {
public:
    vector<string> split(string& path, char ch){
        int index = 0;
        vector<string> res;
        while(index < path.length()){
            while(index < path.length() && path[index] == /) index++;
            if(index >= path.length()) break;
            int start=index, len = 0;
            while(index < path.length() && path[index]!=/) {index++;len++;}
            res.push_back(path.substr(start,len));
        }
        return res;
    }
    
    string simplifyPath(string path) {
        vector<string> a = split(path,/);
        vector<string> file;
        for(int i = 0 ; i < a.size(); ++ i){
            if(a[i] == ".." ){
                if(!file.empty()) file.pop_back();
            }
            else if(a[i]!=".") file.push_back(a[i]);
        }
        string res="";
        if(file.empty()) res ="/";
        else{
            for(int i = 0 ; i < file.size(); ++ i) res+="/"+file[i];
        }
        return res;
    }
};

 

Leetcode Simplify Path,布布扣,bubuko.com

Leetcode Simplify Path

标签:style   blog   color   strong   art   for   

原文地址:http://www.cnblogs.com/xiongqiangcs/p/3847486.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!