Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time

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

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

In a UNIX-style file system, a period ('.') refers to the current directory, so it can be ignored in a simplified path. Additionally, a double period ("..") moves up a directory, so it cancels out whatever the last directory was. For more information, look here: https://en.wikipedia.org/wiki/Path_(computing)#Unix_style

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

My code:

class Solution:
    def simplifyPath(self, path):
        """
        :type path: str
        :rtype: str
        """
        lists=[]
        check_label=False
        i=0
        while i<len(path):
            if check_label==False and path[i]=='/':
                start_index=i+1
                check_label=True
                i=i+1
                continue
            if check_label==True and path[i]=='/':
                i=i+1    
                continue
            if check_label:
                j=i
                while j<len(path):
                    if path[j]=='/':
                        break
                    j=j+1
                tmp_str=path[i:j]
                if tmp_str=='.':
                    i=j
                    check_label=False
                    continue
                if tmp_str=='..':
                    if len(lists)>0:
                        lists.pop()
                    i=j
                    check_label=False
                    continue
                lists.append(tmp_str)
                i=j
                check_label=False
        final_Str=''
        for item in lists:
            final_Str=final_Str+'/'+item
        if final_Str=='':
            final_Str='/'
        return final_Str

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