LeetCode71. 简化路径

☆☆思路:使用字符串的split方法,以'/'为分隔符区分字符,然后逐步识别符号'..'与字母,'.'可以直接忽略,还需要注意空的情况。

class Solution {
    public String simplifyPath(String path) {
        // 需要注意连着的// 分出来是空
        String[] pathArray = path.split("/");
        Stack<String> stack = new Stack<>();

        for (String s : pathArray) {
            if ("..".equals(s)) {
                if (!stack.isEmpty()) stack.pop();
            }else if (!".".equals(s) && !s.isEmpty()) {
                stack.push(s);
            }
        }
        StringBuilder sb = new StringBuilder();
        while (!stack.isEmpty()) {
            sb.insert(0, stack.pop());
            sb.insert(0, "/");
        }
        return sb.length() == 0 ? "/" : sb.toString();
    }
}
原文地址:https://www.cnblogs.com/HuangYJ/p/14155397.html