LeetCode - simplify-path

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/toward_south/article/details/89789428

题目:

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.中间有.直接去掉,

2.有.. 删除上一级的字符

3.两个// ,要删除一个

解题思路:

可以使用栈来解决。我们先把给的参数中"/"去掉,然后遍历这个字符串数组,每当遍历到当前字符串等于".."时,将其出栈,

当遇到".","",".."时,跳过当前字符串,然后将其他的字符串加入栈中

最后记得将栈逆反

提醒:

这里可以使用JDK8的String.join()方法,每隔一个字符串就加入一个"/",有兴趣的朋友可以深入了解下。

下面给出代码:

public static  String simplifyPath(String path) {
        if(path == null || path.length() == 0) {
        	return null;
        }
        
        String[] str = path.split("/");
        LinkedList<String> list = new LinkedList<String>();
        for(String temp : str) {
        	if(!list.isEmpty() && temp.equals("..")) {
        		list.pop();
        	}
        	else if(!temp.equals(".") && !temp.equals("") && !temp.equals("..")) {
        		list.push(temp);
        	}
        }
        Collections.reverse(list);
        return "/"+String.join("/",list);
    }


 

猜你喜欢

转载自blog.csdn.net/toward_south/article/details/89789428
今日推荐