leetcode-71. Simplify Path

leetcode-71. Simplify Path

题目:

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

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

这是一道简单题,基本的方法就是先按照”/”来分割,然后用栈。其实用FIFO更好来按照不同的内容来添加或者删除。直到遍历完String数组。

public class Solution {
    public String simplifyPath(String path) {
        String[] paths = path.split("/");
        Stack sta = new Stack();
        for(String s : paths){
            if(s.equals(".")||s.equals("")){
                continue;
            }else if(s.equals("..")){
                if(sta.size()!=0)
                    sta.pop();
            }else{
                sta.push(s);
            }
        }

        StringBuilder sb = new StringBuilder();
        while(sta.size()!=0){
            sb.insert(0,"/"+sta.pop());
        }
        return sb.length()==0?"/":sb.toString();
    }
}

你可能感兴趣的:(JAVA,leetcode,leetcode,java)