a in-place solution faster than 99%


  • 0
    J

    some badass interviewers might ask you to do this problem in place rather than using a stack... so this is a in-place solution...

    public class Solution {
        public String simplifyPath(String path) {
            if(path == null || path.length() == 0) return "/";
            char[] paths = path.toCharArray();
            int ptr1 = 0, ptr2 = 1;
            while(ptr2 < paths.length){
                int start = ptr2;
                while(ptr2 < paths.length && paths[ptr2] != '/'){
                    ptr2++;
                }
                String name = path.substring(start, ptr2);
                if(name.equals("..")){
                    if(ptr1 != 0){
                        ptr1--;
                        while(ptr1 >= 0 && paths[ptr1] != '/'){
                            ptr1--;
                        }
                    }
                }else if(name.length() != 0 && !name.equals(".")){
                    paths[ptr1] = '/';
                    ptr1++;
                    for(int i=0; i<name.length(); i++){
                        paths[ptr1] = name.charAt(i);
                        ptr1++;
                    }
                }
                ptr2++;
            }
            StringBuilder sb = new StringBuilder();
            for(int i=0; i<ptr1; i++){
                sb.append(paths[i]);
            }
            return sb.length() == 0 ? "/" : sb.toString();
        }
    }
    

Log in to reply
 

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