LeetCode#71. Simplify Path(C++)

  • Question: Given the absolute directory path of a Unix system, return the simplified path. For example:
    path = “/home/”, => “/home”
    path = “/a/./b/../../c/”, => “/c”
  • Difficulty: Medium
  • Idea: split the input string with "/", traverse the split elements, if it is ".", continue; if it is ".." and the previous element contains a directory, pop the top element of the stack, otherwise the current When the element is not "..", the element is pushed onto the stack.
  • Code:
    C++ version
class Solution {
public:
    string simplifyPath(string path) {
        string res;
        string tmp;
        vector<string> vec;
        stringstream ss(path);
        while(getline(ss,tmp,'/')){
            if(tmp == "" or tmp == ".") continue;
            if(tmp == ".." and !vec.empty()){
                vec.pop_back();
            }else if(tmp != ".."){
                vec.push_back(tmp);
            }
        }
        for(string str:vec){
            res += "/" + str;
        }
        return res.empty()?"/":res;
    }
};

Java Edition

class Solution {
    public String simplifyPath(String path) {
        String[] res = path.split("/");
        LinkedList<String> stack = new LinkedList<String>();
        //System.out.print(res);
        for(String str:res){

            if((str.equals(".")) || (str.equals(""))){
                //System.out.println(str);
                continue;
            }
            if((str.equals("..")) && (!stack.isEmpty())){
                stack.pollLast();
            }else if(!str.equals("..")){
                stack.offer(str);
            }
        }
        String result = "";

        while(!stack.isEmpty()){
            result += "/" + stack.pollFirst();
        }
        return result.equals("")?"/":result;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325606697&siteId=291194637