71. Simplify Path | Java最短代码实现

原题链接: 71. Simplify Path

【思路】

本题考查字符串和栈的基本操作。本身并不难:

    public String simplifyPath(String path) {
        Stack<String> stack = new Stack<String>();
        String temp = "";
        for (int i = 0; i < path.length(); i++) {
            while (i < path.length() && path.charAt(i++) == '/')  //跳过'/'
                i++;
            while (i < path.length() && path.charAt(i) != '/') {  //将文件名记录在temp中
                temp += path.charAt(i);
                i++;
            }
            if (temp.equals("..") && !stack.isEmpty())  //如果为"..",且栈不空,弹出第一个(返回上一级目录)
                stack.pop();
            else if (!temp.equals(".") && !temp.equals("..") && !temp.equals(""))  //入栈
                stack.add(temp);
            temp = "";
        }
        while (!stack.isEmpty())
            temp = "/" + stack.pop() + temp;
        return temp == "" ? "/" : temp;
    }
252 / 252  test cases passed. Runtime: 11 ms  Your runtime beats 63.37% of javasubmissions.
欢迎优化!

你可能感兴趣的:(java,LeetCode,栈)