Python State Machine Solution


  • 0
    Z
    
    INIT = -1
    DOT = 0
    SLASH = 1
    ALPHA = 2
    DOT2 = 3
    
    class StateMachine(object):
        def __init__(self):
            self.paths = []
            self.start = 0
            self.state = INIT
        
        def transfer(self, i, c, path):
            
            if self.state == INIT:
                if c == '/':
                    self.state = SLASH
                elif c == '.':
                    self.start = i
                    self.state = DOT
                else:
                    self.state = ALPHA
                    self.start = i
    
            elif self.state == DOT:
                if c == '.':
                    self.state = DOT2
                elif c == '/':
                    self.state = SLASH
                else:
                    self.state = ALPHA
                
            elif self.state == DOT2:
                if c == '/':
                    self.state = SLASH
                    if self.paths:
                        self.paths.pop()
                # elif c == '.':
                    # pass
                else:
                    self.state = ALPHA
    
            elif self.state == SLASH:
                if c == '.':
                    self.state = DOT
                    self.start = i
                elif c == '/':
                    pass
                else:
                    self.state = ALPHA
                    self.start = i
            else:
                if c == '/':
                    if self.start != i:
                        self.paths.append(path[self.start : i])
    
                    self.state = SLASH
                # else:
                    # pass
    
    class Solution(object):
            
        
        def simplifyPath(self, path):
            """
            :type path: str
            :rtype: str
            """
            
            path += '/'
            
            machine = StateMachine()
    
            for (i, c) in enumerate(path):
                machine.transfer(i, c, path)
            
            return '/' + '/'.join(machine.paths)
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.