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

lintcode-medium-Simplify Path

时间:2016-04-06 07:05:45      阅读:139      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!