71. Simplify Path

Given an absolute path for a file (Unix-style), simplify it.

For example,
path="/home/", =>"/home"
path="/a/./b/../../c/", =>"/c"

思路:用stack。以及sss.split("/") 和 sss.equals("..")

public class Solution {
    public String simplifyPath(String path) {
        Stack<String> stack = new Stack<String>();
        String[] p = path.split("/");
        for (int i=0;i<p.length;i++){
            if (!stack.isEmpty() && p[i].equals("..")){
                stack.pop();
            }else if(!p[i].equals(".")&& !p[i].equals("..")&& !p[i].equals("")){
                stack.push(p[i]);
            }
        }
        List<String> list = new ArrayList<String>(stack);
        StringBuilder res = new StringBuilder();
        res.append("/");
        int count = 0;
        for (String element : list){
            if (count > 0)
                res.append("/");
            res.append(element);
            count++;
        }
        return res.toString();
    }
}

results matching ""

    No results matching ""