[LeetCode]Simplify Path

public class Solution {
    public String simplifyPath(String path) {
        String[] strs = path.split("/");
        Stack<String> stack = new Stack<String>();
        for (int i = 0; i < strs.length; i++) {
            if (strs[i].equals("..")) {
                if (!stack.isEmpty())
                    stack.pop();
            } else if (strs[i].equals(".") || strs[i].length() == 0) {
                continue;
            } else {
                stack.push(strs[i]);
            }
        }
        StringBuffer r_b = new StringBuffer("");
        while (!stack.isEmpty()) {
            r_b.insert(0, "/" + stack.pop());
        }
        String result = String.valueOf(r_b);
        if (result.length() == 0) {
            return "/";
        }
        return result;
    }
}

 

posted @ 2015-12-06 08:05  Weizheng_Love_Coding  阅读(105)  评论(0编辑  收藏  举报