您的位置:首页 > 其它

Simplify Path

2016-12-17 22:03 281 查看
题目:

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"
.

思路:

当遇到“/../"则需要返回上级目录,需检查上级目录是否为空。

当遇到"/./"则表示是本级目录,无需做任何特殊操作。

当遇到"//"则表示是本级目录,无需做任何操作。

当遇到其他字符则表示是文件夹名,无需简化。

当字符串是空或者遇到”/../”,则需要返回一个"/"。当遇见"/a//b",则需要简化为"/a/b"。

当字符串为空或者为".",不做任何操作。当字符串不为"..",则将字符串入list。当字符串为"..", 则删除最后一个(返回上级目录)。

[java] view
plain copy

public class Solution {  

    public static String simplifyPath(String path) {  

        String strs[] = path.split("/");  

        LinkedList<String> list = new LinkedList<>();  

        for (String str : strs) {  

            if (str.equals("..") && !list.isEmpty()) {  

                list.removeLast();  

            } else if (!str.equals(".") && !str.equals("") && !str.equals("..")) {  

                list.add(str);  

            }  

        }  

  

        StringBuilder result = new StringBuilder();  

        while (!list.isEmpty()) {  

            result.append("/");  

            result.append(list.removeFirst());  

        }  

        if (result.length() == 0) {  

            return "/";  

        }  

        return result.toString();  

    }  

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: