71. Simplify Path

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

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

public class Solution {
    public String simplifyPath(String path) {
        String[] dirs = path.split("/");
        List<String> list = new LinkedList<>();
        for(String s : dirs){
            if(s == null || s.length() == 0) continue;
            if("..".equals(s)){
                if(!list.isEmpty()) list.remove(list.size()-1);
            }else if(!(".".equals(s))){
                list.add(s);
            }
        }
        if(list.size() == 0) return "/";

        StringBuilder sb = new StringBuilder();
        for(String x : list){
            sb.append('/');
            sb.append(x);
        }
        return sb.toString();

    }
}

results matching ""

    No results matching ""