congr / world

2 stars 1 forks source link

LeetCode : 71. Simplify Path #413

Closed congr closed 5 years ago

congr commented 5 years ago

https://leetcode.com/problems/simplify-path/

image

congr commented 5 years ago

Accepted, but too dirty code.

class Solution {
    public String simplifyPath(String path) {
        String res = path.replace("//", "/");
        res = res.replace("..", "+");
        res = res.replace("//", "/");
         res = res.replace("//", "/");
         res = res.replace("//", "/");

        if (res.equals("/") || res.equals("//")) return "/";

        String[] sp = res.split("/");
        ArrayList<String> list = new ArrayList();
        list.add("/");
        for (int i = 0; i<sp.length; i++) {
            String s = sp[i];
            if (s.equals(".") || s.equals(" ")) continue;
            if (s.equals("+")) {
                list.remove(list.size()-1);
                if (list.size() == 0) list.add("/"); 
            } else list.add(s);
        }

        StringBuilder sb = new StringBuilder();
        list.remove(0);
        for(String s: list) {
            if (s.equals(" ") || s.length() == 0) continue;
            sb.append("/");
            sb.append(s.trim());
        }

        if (sb.length() == 0) return "/";

        String result = sb.toString();
        result = result.replace("+", "..");
        return result;
    }
}
congr commented 5 years ago

better code

class Solution {
    public String simplifyPath(String path) {
        String res = path.replaceAll("/+", "/");
        String[] sp = res.split("/");

        Stack<String> st = new Stack();
        for (String s : sp) {
            if (s.equals("..")) {
                if (!st.isEmpty()) st.pop();
            } else if (s.equals(".") || s.isEmpty()) continue;
            else st.push(s);
        }

        String simple = "";
        while (!st.isEmpty()) simple = "/" + st.pop() + simple;

        return simple.isEmpty() ? "/" : simple;
    }
}