LeetCode問題解(16):Simplify Path


タイトル:
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" .

  • 問題:
    1.入力文字列を'/'で区切り文字に分割して文字列配列に保存する
    2.1で生成された文字列の配列を巡回し、非"."およびの文字列は、その文字列の前に"/"を付けて、1つの文字列スタックに押し込みます(vectorで実現して、最後のパッチパスを便利にします)
    に出会うたびにの場合、直接continue
    に会うたびにスタックから要素がポップアップされます
    3.ループが完了したら、スタック内の残りの文字列を先に出した順序(vectorで要素に両端アクセス可能)で最後のパスにつなぎます.
    スタックが空の場合は、/(/)を返します.
    class Solution {
    public:
        string simplifyPath(string path) {
            if(!path.length())
                return path;
            vector<string> split;
    
            for(int i = 0; i < path.length();)
            {
                if(path[i] == '/')
                {
                    i++;
                    continue;
                }
                else {
                    string temp = "";
                    while(path[i] != '/' && i < path.length())
                    {
                        temp.insert(temp.length(), 1, path[i++]);
                    }
                    split.push_back(temp);
                }
            }
            
            vector<string> combine;
            for(int i = 0; i < split.size(); i++)
            {
                if(split[i] != "." && split[i] != "..")
                {
                    string path1 = "";
                    path1.insert(path1.length(), 1, '/');
                    path1.insert(path1.length(), split[i]);
                    combine.push_back(path1);
                }
                else if(split[i] == ".." && combine.size())
                {
                    combine.pop_back();
                }
                else{
                    continue;
                }
            }
            
            string final = "";
            if(!combine.size())
            {
                final.insert(final.length(), 1, '/');
            }
            for(int i = 0; i < combine.size(); i++)
            {
                final.insert(final.length(), combine[i]);
            }
            return final;
        }
    };