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

Simplify Path

时间:2015-04-05 23:29:44      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/simplify-path/

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

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

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

click to show corner cases.

Corner Cases:
  • 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".

解题思路:

1. 用split将path分段

2. 将分段的结果存入list

3. 从list的第二个元素开始,遇到"."和空,删除它;遇到"..",删除它,再删除前一个元素(如果前一个元素>0)。

4. 从头遍历list,组成结果

public class Solution {
    public String simplifyPath(String path) {
        String[] strs = path.split("/");
        List<String> list = new LinkedList<String>();
        for(int i = 0; i < strs.length; i++) {
            list.add(strs[i]);
        }
        //split方法的第一个元素肯定是空,所以从第二个元素开始
        for(int i = 1; i < list.size(); i++) {
            if(list.get(i).equals(".") || list.get(i).length() == 0) {
                list.remove(i);
                i--;
            }
            if(list.get(i).equals("..")) {
                list.remove(i);
                if(i - 1 >= 1) {
                    list.remove(i - 1);
                    i = Math.max(0, i - 2);
                }else {
                    i--;
                }
            }
        }
        String result = "";
        for(int i = 1; i < list.size(); i++) {
            result += "/" + list.get(i);
        }
        if(result.length() == 0){
            result = "/";
        }
        return result;
    }
}

也可以直接借助split后的数组做。

public class Solution {
    public String simplifyPath(String path) {
        String[] strs = path.split("/");

        //split方法的第一个元素肯定是空,所以从第二个元素开始
        for(int i = 1; i < strs.length; i++) {
            if(strs[i].equals(".") || strs[i].equals("")) {
                strs[i] = "#";
            }
            if(strs[i].equals("..")) {
                strs[i] = "#";
                int j = i - 1;
                while(j >= 1 && strs[j].equals("#")) {
                    j--;
                }
                if(j >= 1) {
                    strs[j] = "#";
                }
            }
        }
        String result = "";
        for(int i = 1; i < strs.length; i++) {
            if(!strs[i].equals(".") && !strs[i].equals("#")) {
                result += "/" + strs[i];
            }
        }
        if(result.length() == 0){
            result = "/";
        }
        return result;
    }
}

 

Simplify Path

标签:

原文地址:http://www.cnblogs.com/NickyYe/p/4394941.html

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