[20190709] [one algorithm problem per day] valid brackets (stacks)

Keywords: Python

problem

Given a string that only includes' (',' '', '{', '}', '[', ']', to determine whether the string is valid.

A valid string must satisfy the following: the opening bracket must be closed with the same type of closing bracket; the opening bracket must be closed in the correct order.

Note: an empty string can be considered a valid string.

Example 1:

Input: '()', output: true
Example 2:

Input: '() [] {}', output: true
Example 3:

Input: '(]', output: false
Example 4:

Input: '([)]', output: false
Example 5:

Input: '{[]}', output: true

Ideas and answers

1. Python implementation

# Method 1: stack operation without hash table
# Read the string s one by one. If the stack is empty, the element will be pushed into the stack. If the stack is not empty, then compare whether the current element matches the top element of the stack. If it matches, the top element will pop up. If it does not match, it will be pushed into the stack. Finally, judge whether the stack is empty.
# Time complexity: O(n)
class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        if s == []: 
            return True
        elif len(s) % 2 != 0: 
            return False
        else:
            for ch in s:
                if stack == []:
                    stack.append(ch)
                else:
                    if ch == ")" and stack[-1] == "(":   # stack[-1] refers to the top element of stack (because the last element of [- 1] index string)
                        stack.pop()
                    elif ch == "]" and stack[-1] == "[":
                        stack.pop()
                    elif ch == "}" and stack[-1] == "{":
                        stack.pop()
                    else:
                        stack.append(ch)
            return stack == []
################## My original way of writing ####################
#### It's wrong, because stacks are not built-in types of python, so you need to use Python lists to simulate array based stacks. Lists can only be used with. append() and. pop(), while stack operations. peek() and. isEmpty() cannot be used directly.
class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        if s == []: 
            return True
        elif len(s) % 2 != 0: 
            return False
        else:
            for ch in s:
                if stack == []:
                    stack.push(ch)
                else:
                    if ch == "(" and stack.peek() == ")":
                        stack.pop()
                    elif ch == "[" and stack.peek() == "]":
                        stack.pop()
                    elif ch == "{" and stack.peek() == "}":
                        stack.pop()
                    else:
                        stack.push(ch)
            return stack.isEmpty()


# Method 2: stack operation, using hash table (applicable to cases with many symbol types)
# Hash the matching symbols (Note: the ones to be reversed are first!) , and then determine whether the current element is in the hash table. If it is not, press it directly into the stack. If it is in the hash table, compare the top element of the stack with the value corresponding to the key in the hash table. If it is different, return False.
# Time complexity: O(n)
class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        hashmap = {")" : "(", "]" : "[", "}" : "{"}   # Create a hash table. Note: symbols are all reversed!
        for ch in s:
            if ch in hashmap:   # Determine whether ch exists in hash table (. keys())
                top = stack.pop() if stack else "#"  # If the stack is empty, the top element of the stack is set to '#’(as long as it is not the symbol in the title)
                # if hashmap[ch] == top:     # This is not possible because the element cannot be ejected when the stack is empty
                #     stack.pop()       
                if hashmap[ch] != top:
                    return False
            else:
                stack.append(ch)
        return not stack
		
''' Contact: write the reverse symbol first, and write the positive symbol; difference: first, judge before stack, second, judge before stack '''

 

 

Posted by lucifersolutions on Thu, 31 Oct 2019 10:16:03 -0700