Java Solution with Stack


  • 0
    A

    public class Solution {
    public String simplifyPath(String path) {

        String[] paths = path.split("/");
        Stack<String> stack = new Stack<>();
        for(String str: paths) {
            if(str.equals(".") || str.trim().length() == 0) {
                continue;
            } else if (str.equals("..")) {
                if(!stack.isEmpty()) {
                    stack.pop();
                }
            } else {
                stack.push(str);
            }
        }
        
        StringBuilder sb = new StringBuilder();
        while(!stack.isEmpty()) {
            sb.insert(0, stack.pop());
            sb.insert(0, "/");
        }
        return sb.toString().length() == 0 ? "/":sb.toString();
    }
    

    }


Log in to reply
 

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