LeetCode刷题记81-71. 简化路径

LeetCode刷题记81

71. 简化路径

题目
LeetCode刷题记81-71. 简化路径

class Solution {
    public String simplifyPath(String path) {
        String ans = "";
        Stack<String> sta = new Stack<String>();
        String[] dirs = path.split("/+");
        for (String s : dirs) {
            //System.out.println("k" + s);
            if (s.length() > 0) {
                if (s.length() == 1 && s.charAt(0) == '.') {
                    continue;
                } else if (s.length() == 2 && s.charAt(1) == '.') {
                    if (sta.isEmpty() == true) {
                        continue;
                    } else {
                        sta.pop();
                    }
                } else {
                    sta.push(s);
                }
            }
        }
        for (String s : sta) {
            ans += "/" + s;
        }
        if (ans.length() == 0) ans = "/";
        return ans;
    }
}

3/5
81/150

上一篇:单调栈及其应用


下一篇:csacademy Squared Ends 题解(动态凸包/李超树/分治/二进制技巧