首页 > 技术文章 > LeetCode OJ-- Simplify Path **

qingcheng 2014-06-19 14:55 原文

https://oj.leetcode.com/problems/simplify-path/

对linux路径的规范化,属于字符串处理的题目。细节很多。

#include <iostream>
#include <string>
using namespace std;

class Solution {
public:
    string simplifyPath(string path) {
        if(path == "/../")
            return "/";
        
        int len = path.length();
        // if last was ..,then regard it as ../
        if(len>=2 && path[len-1]=='.'&& path[len-2] == '.')
            path.append("/");
        len = path.length();

        string ans = "/";        
        int pos = 1;
        int pos2;
        while(1)
        {
            //unfind is -1
            pos2 = path.find_first_of('/',pos);
            
            //two '//', ignore
            if(pos2!= -1 && path[pos2-1]=='/')
            {
                pos = pos2+1;
                continue;
            }
            //exit test,means not find
            //handle the left eg:/a/b/cc
            if(pos2 == -1 )
            {
                string subStr = path.substr(pos,pos2-pos+1);
                if(subStr == "." || subStr == "..")
                    break;
 
                ans.append(subStr);
                break;
            }
            //if ../
            if(pos2>=2 && path[pos2-1] == '.' && path[pos2-2] == '.' && pos2-2 == pos)
            {
                int pos3 = ans.rfind('/',ans.size()-2);
                if(pos3>=0)
                    ans = ans.substr(0,pos3+1);
                pos = pos2 +1;
                continue;
            }
            //if ./
            if(pos2>=2&&path[pos2-1] == '.'&& pos == pos2-1)
            {
                pos = pos2+1;
                continue;
            }

            string subStr = path.substr(pos,pos2 - pos +1);
            ans.append(subStr);
            pos = pos2 + 1;

        }
        //remove the last /
        int t = ans.length()-1;
        while(t>0)
        {
            if(ans[t]=='/')
                t--;
            else
                break;
        }


        ans = ans.substr(0,t+1);

        return ans;
    }
};

int main()
{ 
    class Solution myS;
    cout<<myS.simplifyPath("/b/DfZ/AT/ya///./../.././..")<<endl;
    return 0;
}

 

推荐阅读