LeetCode71. Simplify Path(C++)

Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.

In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the directory up a level. For more information, see: Absolute path vs relative path in Linux/Unix

Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path.

 

Example 1:

Input: "/home/"
Output: "/home"
Explanation: Note that there is no trailing slash after the last directory name.

Example 2:

Input: "/../"
Output: "/"
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.

Example 3:

Input: "/home//foo/"
Output: "/home/foo"
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.

Example 4:

Input: "/a/./b/../../c/"
Output: "/c"

Example 5:

Input: "/a/../../b/../c//.//"
Output: "/c"

Example 6:

Input: "/a//b////c/d//././/.."
Output: "/a/b/c"

解題思路:將絕對路徑轉化爲最簡的相對路徑

關於‘/’處理:我們需要關注的是斜槓分隔開的每個文件名,所以遇到斜槓直接遍歷到下一個非斜槓的位置,記錄每個文件夾名。

關於".."處理:這是返回上一級文件夾,所以要將我們之前訪問到的文件夾名刪除(如果存在的話)

關於"."處理:指當前文件夾,無需處理,也不要存儲。

class Solution {
public:
    string simplifyPath(string path) {
        vector<string>ans;
        string res = "";
        int i = 0;
        while(i < path.length()){
            string temp = "";
            while(i < path.length() && path[i] == '/')
                ++ i;
            while(i < path.length() && path[i] != '/')
                temp += path[i++];
            if(temp == ".."){
                if(!ans.empty())
                    ans.pop_back();
            }               
            else if(temp != "."&& temp != "")
                ans.push_back(temp);
        }
        if(ans.empty())
            res = "/";
        for(int i = 0; i < ans.size(); ++ i)
            res += '/' + ans[i];
        return res;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章