题解 | #简化目录路径#

简化目录路径

http://www.nowcoder.com/practice/3177bcbfd947409ba833efb5a5b4a24c

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param path string字符串 
     * @return string字符串
     */
    public String simplifyPath (String path) {
        // write code here
        String[] strs = path.split("/");
        Stack<String> stack = new Stack<>();
        for (String str: strs) {
            if (str.equals("..")) {
                if (!stack.isEmpty()) {
                    stack.pop();
                }
            }
            else if (!(str.equals(".") || str.equals(""))) {
                stack.push(str);
            }
        }
        String res = "";
        while (!stack.isEmpty()) {
            res = "/" + stack.pop() + res;
        }
        return res.length() == 0 ? "/" : res;
    }
}
全部评论

相关推荐

爱写代码的菜code...:哎,自己当时拿到字节offer的时候也在感叹终于拿到了,自己当时最想去的企业就是字节,结果还是阴差阳错去了鹅厂。祝uu一切顺利!!!
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务