卖萌的弱渣

I am stupid, I am hungry.

Simplify Path

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

Example

  • path = “/home/”, => “/home”
  • path = “/a/./b/../../c/”, => “/c”

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

Solution

  • Java
(Simplify-path.java) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Solution {
    public String simplifyPath(String path) {
        Deque<String> stack = new LinkedList<String>();

        for (String s : path.split("/")){
            if(s.equals(".") || s.equals(""))
                continue;
            if(s.equals("..")){
                if(!stack.isEmpty())
                    stack.pop();
                continue;
            }

            stack.push(s);

        }
    // 生成字符串时要从stack的底部开始       
    String res = "";
    for (String dir : stack) res = "/" + dir + res;
    return res.isEmpty() ? "/" : res;
    }
}
  • Python
(Simplify-Path.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution(object):
    def simplifyPath(self, path):
        """
        :type path: str
        :rtype: str
        """
        ret = ""
        if path == None or len(path) == 0:
            return
        paths = path.split('/')
        stack = []
        for i in paths:
            if i == "..":
                if len(stack) != 0:
                    stack.pop()
            elif i == "." or i =="":
                continue
            else:
                stack.append(i)
        ret = '/'+'/'.join(stack)
        return ret