Lintcode 421. Simplify Path (Medium) (Python)

Simplify Path

Description:

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

Code:

class Solution:
    """
    @param path: the original path
    @return: the simplified path
    """
    def simplifyPath(self, path):
        # write your code here
        path = path.split('/')
        cur = '/'
        for i in path:
            if i == '..':
                if cur!='/':
                    cur = '/'.join(cur.split('/')[:-1])
                    if cur == '':
                        cur = '/'
            elif i!='.' and i!='':
                if cur!='/':
                    cur = cur + '/' + i
                else:
                    cur = cur + i
        return cur

猜你喜欢

转载自blog.csdn.net/weixin_41677877/article/details/82497107
今日推荐