首页 > 其他 > 详细

lintcode-medium-Simplify Path

时间:2016-04-06 07:03:29      阅读:277      评论:0      收藏:0      [点我收藏+]

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

 

Example

"/home/", => "/home"

"/a/./b/../../c/", => "/c"

Challenge
  • Did you consider the case where path = "/../"?

    In this case, you should return "/".

  • Another corner case is the path might contain multiple slashes ‘/‘together, such as "/home//foo/".

    In this case, you should ignore redundant slashes and return"/home/foo".

 

public class Solution {
    /**
     * @param path the original path
     * @return the simplified path
     */
    public String simplifyPath(String path) {
        // Write your code here
        
        if(path == null || path.length() == 0)
            return path;
        
        Stack<String> stack = new Stack<String>();
        
        int i = 0;
        int j = 1;
        int len = path.length();
        
        while(j < len){
            
            while(j < len && path.charAt(j) != ‘/‘)
                j++;
            
            String temp = path.substring(i, j);
            
            if(temp.equals("/.") || temp.equals("/")){
                i = j;
                j++;
            }
            else if(temp.equals("/..")){
                if(!stack.isEmpty())
                    stack.pop();
                
                i = j;
                j++;
            }
            else{
                stack.push(temp);
                i = j;
                j++;
            }
        }
        
        if(stack.isEmpty())
            return "/";
        
        String res = "";
        
        while(!stack.isEmpty()){
            res = stack.pop() + res;
        }
        
        return res;
    }
}

 

lintcode-medium-Simplify Path

原文:http://www.cnblogs.com/goblinengineer/p/5357665.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!