码迷,mamicode.com
首页 > 其他好文 > 详细

Simplify Path

时间:2014-11-25 00:23:38      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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

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

算法:根据/把path分割,再逐个判断

public class Solution {
    public String simplifyPath(String path) {
        String[] strs = path.split("/");
        Stack<String> s = new Stack<String>();
        for(int i=0;i<strs.length;i++){
            if(strs[i].equals(".")){
            }else if(strs[i].equals("..")){
                if(!s.isEmpty())
                    s.pop();
            }else if(strs[i].length()>0){
                s.push(strs[i]);
            }
        }
        StringBuilder sb = new StringBuilder();
        Iterator<String> it = s.iterator();
        while(it.hasNext()){
            String t = it.next();
            sb.append("/").append(t);
        }
        String r=sb.toString();
        if(r.length()==0)
            r+="/";
        return r;
    }
}





Simplify Path

标签:leetcode

原文地址:http://blog.csdn.net/u010786672/article/details/41456083

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!