[leedcode 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) {
        /*这道题目是Linux内核中比较常见的一个操作,就是对一个输入的文件路径进行简化。
        思路比较明确,就是维护一个栈,对于每一个块(以‘/’作为分界)进行分析,如果遇到‘../’则表示要上一层,那么就是进行出栈操作,
        如果遇到‘./’则是停留当前,直接跳过,其他文件路径则直接进栈即可。
        最后根据栈中的内容转换成路径即可。
        时间上不会超过两次扫描(一次是进栈得到简化路径,一次是出栈获得最后结果),所以时间复杂度是O(n),空间上是栈的大小,也是O(n)。*/
        Stack<String> stack=new Stack<String>();
        int start=0;
        for(int i=0;i<=path.length();i++){//注意i的范围。针对这种输入"/home",需要读取到最后一位,所以i可以为len
            if(i<path.length()&&path.charAt(i)!='/'){continue;}
            if(start<i){//注意判断
                 String temp=path.substring(start,i);
                if(temp.equals("..")){
                    if(!stack.empty())//注意判断,不为空才可以弹出
                      stack.pop();
                }else{
                    if(temp.equals(".")){
                        start=i+1;//注意更新start为下一个不为/'的索引
                        continue;
                    }
                    else{
                        stack.push(temp); 
                    }
                }
                
            }
            start=i+1; 
        }
        StringBuilder res=new StringBuilder();
        if(stack.empty()) res.append("/");//注意考虑栈空的情况
        while(!stack.empty()){
            String temp=stack.pop();
            res.insert(0,"/"+temp);//头插
            
            
        }
        return res.toString();
    }
}

 

posted @ 2015-07-13 23:02  ~每天进步一点点~  阅读(160)  评论(0编辑  收藏  举报