3ms Java solution beats 100%!


  • 0
    C

    In a real interview, I met this problem and was requested to solve it in place without using any extra linear space like stack or another array. I was not able to figure it out clearly in that interview and found this solution later as below:

    public class Solution {
            // for an in place solution, the type of parameter should be char[],  
            // use String to make it can be accepted in Java.
            public String simplifyPath(String strPath) {  
            if(strPath == null || strPath.charAt(0) != '/') {
                return null;
            }
            char[] path = strPath.toCharArray();
            int last = 0, start = 0, cur = 0;
            for(; start < path.length; cur++) {
                if((cur < path.length && path[cur] == '/') || cur == path.length) {
                    if(cur - start == 3 && path[cur-1] == '.' && path[cur-2] == '.') {
                        while(last > 0 && path[--last] != '/') ;
                    } else if(cur - start > 2 || (cur-start == 2 && path[cur-1] != '.')) {
                        while(start < cur) {
                            path[last++] = path[start++];
                        }
                    }
                    start = cur;
                }
            }
            if(last == 0) {
                path[last++] = '/';
            }
            return new String (path, 0, last);
        }
    }

  • 0
    N
    This post is deleted!

Log in to reply
 

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