Thursday, October 3, 2013

71. Simplify Path ---------M

Q:
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".
A:


------------------第二遍, 学乖了,直接用了个split函数-----------

class Solution {
public:
    string simplifyPath(string path) {
        vector<string> V;
        int start = 0, end = 0;
        int n = path.length();
        while(start < n){
            // update start till it is not /
            while(start<n && path[start] == '/'){
                start++;
            }
            end = start+1;
            while(end<n && path[end] != '/'){
                end++;
            }
            string folder = path.substr(start, end-start);
            if(folder.length() == 0 || folder=="."){ // ignore
            }else if(folder ==".."){
                if(V.size()>0){
                    V.pop_back();
                }
            }else{
                V.push_back(folder);
            }
            start = end+1;
        }
        if(V.empty())
            return "/";
        string res = "";
        for(auto folder:V){
            res += "/" + folder;
        }
        return res;
    }
};

Mistakes:
1: 没有考虑,当buf为空的时候,我们仍然要输出一个"/"
2:    split()函数不太明白。   对于“/..."这个来讲,分出的是两个string { "","..."}
        因此,我们需要处理curPath为空的情况。


 --------------1st pass-------------------
这道题就不是考 难度的,是考 细心!!!!!!!!!!!!!!!!!


Mistakes:
 1:取 substring的时候,忘记把 lastSlashPos 的位置+1了。  导致,总是包括了两个//
 2:  Did you consider the case where path = "/../"?
       In this case, you should return "/".
 当上述情况时,我们不能太简单的删除last element of ArrayList, 而应该检查是否是到了根节点了(ArrayList.isEmpty()。)
3: 当 ArrayList为空时, 还是要输出一个  "/" 的, 哎, 竟然这样SB的错误啊~~~~~~~~
4: 没有考虑,当最后的是 “."   ".."的情况,╮(╯▽╰)╭
   太SB得直接append到ArrayList上了。
5: path.substring(lastSlashPos+1);    这里也是要加一的。 ╮(╯▽╰)╭
全线SB啊,Tiger

 Learned:



No comments:

Post a Comment