Java 10-line solution without stack


  • 0

    Here is my solution without using stack. Just process backwards with a counter "skip". I think it's as concise as solution using stack. :)

        public String simplifyPath(String path) {
            StringBuilder result = new StringBuilder();
            String[] dirs = path.split("/");
            for (int i = dirs.length - 1, skip = 0; i >= 0; i--) {
                if (dirs[i].equals("..")) skip++;
                else if (!dirs[i].isEmpty() && !dirs[i].equals(".")) {
                    if (skip > 0) skip--;
                    else result.insert(0, "/" + dirs[i]);
                } /*else dirs[i] == "" or "." */
            }
            return result.length() == 0 ? "/" : result.toString();
        }
    

Log in to reply
 

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