Java already has the method String.join


  • 1
    T
    public String simplifyPath(String path) {
        Stack<String> stack = new Stack<String>();
        for (String s : path.split("/")) {
            if (s.equals("..") && !stack.isEmpty())
                stack.pop();
            else if (!s.equals(".") && !s.equals("..") && !s.equals(""))
                stack.push(s);
        }
        return "/" + String.join("/", stack);
    }

Log in to reply
 

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