71. Simplify Path

# Medium

Key idea:

  1. extract the string between start'/' and end'/' storing in a string list(only effctive path)

  2. "." do nothing

  3. ".." path2.pop()

Solution:

  1. find the effective start '/'

  2. find the effective end '/', extract string between start and end

  3. if string = '.', do nothing; if string = '..', path2.pop(); else path2.append(string)

  4. convert path2 list to a real path string

class Solution:
    def simplifyPath(self, path: str) -> str:
        i = 0
        path2 = []
        while i < len(path):
            # find start '/', i == start'/'
            while i < len(path) and path[i] == '/':
                i += 1
            if i == len(path):
                break
                
            # find the end '/', i == end'/'
            tmp = ''
            while i < len(path) and path[i] != '/':
                tmp += path[i]
                i += 1
            
            # add to path2
            if tmp == '..':
                if len(path2) != 0:
                    path2.pop()
            elif tmp == '.':
                continue
            else:
                path2.append(tmp)
                
        # convert path2 to canonical path
        if len(path2) == 0: return '/'
        
        c = ''
        for i in range(len(path2)):
            c = c + '/' + path2[i]

        
        return c

Last updated