4ms java with state machine to separate and combine the string


  • 0
    O
    public String simplifyPath(String path){
     if (path.charAt(0) != '/')
                return "";
            int SeqNum = 0;
            int[] SeqLeft = new int[path.length()/2];
            int[] SeqRight = new int[path.length()/2];
            int Status = 1;
    
            for (int i = 1; i < path.length(); i++) {
                if (Status == 0){
                    if (path.charAt(i) == '/'){
                        SeqRight[SeqNum++] = i;
                        Status = 1;
                    }
                }
                else if(Status == 1) {
                    if (path.charAt(i) == '.'){
                        Status = 2;
                        SeqLeft[SeqNum] = i - 1;
                    }
                    else if(path.charAt(i) != '/'){
                        Status = 0;
                        SeqLeft[SeqNum] = i - 1;
                    }
                }
                else if (Status == 2){
                    if (path.charAt(i) == '.'){
                        Status = 3;
                    }
                    else if(path.charAt(i) == '/'){
                        Status = 1;
                    }
                    else{
                        Status = 0;
                    }
                }
                else if (Status == 3){
                    if (path.charAt(i) == '/'){
                        if (SeqNum > 0)
                            SeqNum--;
                        Status = 1;
                    }
                    else{
                        Status = 0;
                    }
                }
            }
    
            if (Status == 0) {
                SeqRight[SeqNum++] = path.length();
            }
            else if (Status == 3) {
                if (SeqNum > 0)
                    SeqNum--;
            }
    
            StringBuilder ans = new StringBuilder();
            for (int i = 0; i < SeqNum; i++) {
                ans.append(path.substring(SeqLeft[i],SeqRight[i]));
            }
            if (SeqNum == 0)
                return "/";
            return ans.toString();
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.