LeetCode 71. Simplify Path

题目

字符串问题

class Solution {
public:
    string simplifyPath(string path) {
        
        string paths[10005];
        int pos=0;
        paths[0]="/";
        string str="";
        for(int i=0;i<path.length();i++)
        {
            if(i==0&&path[i]=='/')
                continue;
            
            if(path[i]=='/')
            {
                if(str=="")
                    continue;
                if(str=="..")
                {
                    if(pos>0){
                        pos--;
                    }
                    str="";
                    continue;
                }
                else if(str==".")
                {
                    str="";
                    continue;
                }
                else
                {
                    str+='/';
                    paths[++pos]=str;
                    str="";
                }
              
            }
            else {
                
                str+=path[i];
            }
        }
        if(str=="..")
        {
            if(pos>0){
            pos--;
            }
        }
        else if(str!=""&&str!=".")
        {
            str+='/';
            paths[++pos]=str;
        }
        
        if(pos!=0){
            
            paths[pos]=paths[pos].substr(0,paths[pos].length()-1);
        }
        
        string ans="";
        for(int i=0;i<=pos;i++)
        {
            ans+=paths[i];
        }
        return ans;
        
    }
};
原文地址:https://www.cnblogs.com/dacc123/p/11584554.html