71.简化路径(其他).java

java
阅读 31 收藏 0 点赞 0 评论 0

Java 10-lines solution with stack.java
public String simplifyPath(String path) {
    Deque<String> stack = new LinkedList<>();
    Set<String> skip = new HashSet<>(Arrays.asList("..",".",""));
    for (String dir : path.split("/")) {
        if (dir.equals("..") && !stack.isEmpty()) stack.pop();
        else if (!skip.contains(dir)) stack.push(dir);
    }
    String res = "";
    for (String dir : stack) res = "/" + dir + res;
    return res.isEmpty() ? "/" : res;
}
71. Simplify Path.java
public class Solution {
    public String simplifyPath(String path) {
        Deque<String> stack = new ArrayDeque<String>();
        int end = 0;
        int len = path.length();
        StringBuilder res = new StringBuilder();
      
        while (end < len) {
            StringBuilder sb = new StringBuilder();
            sb.append(path.charAt(end++));
            while (end < len && path.charAt(end) != '/') {
                sb.append(path.charAt(end++));
            }
            String temp = sb.toString();
            if (temp.equals("/..")) {
                if (stack.isEmpty()) { // "/.."
                    continue;
                }
                stack.pop();
            }
            else if (temp.equals("/.") || temp.equals("/")) continue; //"/home//foo/"
            else {
                stack.push(temp);
            }
        }
        for (String item : stack) {
            res.insert(0, item);
        }
        return res.length() == 0 ? "/" : res.toString();
    }
}



/*
"/"
"/home/"
"/a/./b/../../c/"
"/.."
"/home//foo/"
*/
71. Simplify Path(Others).java
public class Solution {
    public String simplifyPath(String path) {
        int len = path.length();
        Stack<String> tokens = new Stack<String>();
        String sub_str = "";
        for(int i = 0; i < len; i++) {
            if(path.charAt(i) == '/') {
                if(sub_str != "") {
                    tokens.push(sub_str);
                    sub_str = "";
                }
            } else {
                sub_str += path.charAt(i);
            }
        }
        if(sub_str != "") {
            tokens.push(sub_str);
            sub_str = "";
        }
        
        String simp_path = "";
        int pop_last = 0;
        while(!tokens.empty()) {
            String token = tokens.pop();
            if(token.equals(".")) continue;
            else if(token.equals("..")) {
                pop_last++;
                continue;
            } else if(pop_last > 0) {
                pop_last--;
                continue;
            }
            
            if(simp_path == "") simp_path = token;
            else simp_path = token + '/' + simp_path;
        }
        simp_path = '/' + simp_path;
        return simp_path;
    }
}
评论列表


问题


面经


文章

微信
公众号

扫码关注公众号