Clear and fast Java Solution (Beats 99%)


  • 0
    J
    public class Solution {
        public String simplifyPath(String path) {
            path += '/';
            char[] chars = path.toCharArray();
            ArrayList<int[]> paths = new ArrayList<>();
            for (int i = 0, j = 0, dots = 0; i < chars.length; i++) {
                char c = chars[i];
                if (c == '/') {
                    if (i != j) {
                        if (dots == 0 || i - j > dots || dots > 2) {
                            paths.add(new int[]{j, i - j});
                        } else if (dots == 2 && paths.size() > 0) {
                            paths.remove(paths.size() - 1);
                        }
                        dots = 0;
                    }
                    j = i + 1;
                } else if (c == '.') dots++;
            }
            if (paths.size() == 0) return "/";
            StringBuilder sb = new StringBuilder();
            for (int[] p: paths) {
                sb.append('/');
                sb.append(chars, p[0], p[1]);
            }
            return sb.toString();
        }
    }
    

Log in to reply
 

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