Leetcode 71. Simplify Path

Leetcode 71. Simplify Path_第1张图片
方法1: use split() function。时间复杂n,空间复杂n。

class Solution {
    public String simplifyPath(String paths) {
        String sub = paths.substring(1);
        String[] path = sub.split("/");
        StringBuilder sb = new StringBuilder();
        sb.append("/");
        //Stack stack = new Stack<>();
        for(int i = 0; i < path.length; i++){
            String curr = path[i];
            if(curr.equals("") || curr.equals(".")) continue;
            if(curr.equals("..") && sb.length() > 1){
                modify(sb);
            }else if(curr.equals("..") && sb.length() == 1){
                continue;
            }else{
                sb.append(curr + "/");
            }
            
        }
        if(sb.length() > 1) sb.deleteCharAt(sb.length()-1);
        return sb.toString();
    }
    public void modify(StringBuilder sb){
        sb.deleteCharAt(sb.length()-1);
        while(sb.charAt(sb.length()-1) != '/'){
            sb.deleteCharAt(sb.length()-1);
        }
    }
}

方法2: use stack。时间复杂n,空间复杂n。

class Solution {
    public String simplifyPath(String path) {
        Stack<Character> stack = new Stack<>();
        stack.push(path.charAt(0));
        int count = 2;
        boolean flag = false;
        for(int i = 1; i < path.length(); i++){
            char c = path.charAt(i);
            if(c == '/'){
                if(stack.peek() == '/') continue;
                if(stack.peek() == '.' && !flag) {
                   stack.pop();
                    continue;
                }
                if(flag) flag = false;
                stack.push(c);
                continue;
            }
            if(c == '.'){
                if(stack.peek() == '.'){
                    if((i < path.length()-1 && path.charAt(i+1) == '.') || flag){
                        flag = true;
                        stack.push(c);
                        continue;
                    }
                    if((i < path.length()-1 && path.charAt(i+1) != '/') ){
                        stack.push(c);
                        continue;
                    }
                    while(stack.size() > 1 && count > 0){
                        if(stack.pop() == '/') count--;
                    }
                    count = 2;
                }else{
                    stack.push(c);
                }
                continue;
            }
            stack.push(c);
        }
        StringBuilder sb = new StringBuilder();
        while(!stack.isEmpty()) sb.append(stack.pop());
        sb.reverse();
        if(sb.charAt(sb.length()-1) == '.' && sb.charAt(sb.length()-2) == '/') sb.delete(sb.length()-2, sb.length());
        else if(sb.charAt(sb.length()-1) == '/') sb.deleteCharAt(sb.length()-1);
        if(sb.length() == 0) sb.append('/');
        return sb.toString();
    }
}

总结:

你可能感兴趣的:(Leetcode,stack,string)