• LeetCode OJ-- Simplify Path **


    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;
    }
  • 相关阅读:
    6-rocketmq-springboot整合
    5-rocketmq-事务消息
    3-rocketmq-支持的消息种类
    2-rocketmq-消息发送和接收
    1-rocketmq简介-部署
    详解unix5种IO模型
    大纲
    马哥博客作业第二十一周
    马哥博客作业第二十周
    马哥博客作业第十九周
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3796588.html
Copyright © 2020-2023  润新知