def longest_valid_parens(string): stack = Stack() longest = 0 for c in string: if c == '(': stack.push(c) elif c == ')': if not stack.empty(): top = stack.pop() if top == '(': longest += 2 return longest
def shortest_transformation(start, end, dict): assert len(start) == len(end) dict.append(end) root = Node(start, None, 1) stack = Stack() stack.push(root) char_list = [] for i in range(0, len(start)): char_list.append(set([word[i] for word in dict])) added_to_stack = [start] while not stack.empty(): top = stack.pop() original_str = top.data num_transformations = top.transformations + 1 for i in range(0, len(original_str)): for c in char_list[i]: new_str = original_str new_str = new_str.replace(new_str[i], c) if new_str == original_str: continue if new_str == end: # figure out the transformations transformations = [new_str] node = top while node.parent is not None: transformations.append(node.data) node = node.parent transformations.append(start) transformations.reverse() print(" --> ".join(transformations)) return num_transformations if new_str in dict: if new_str not in added_to_stack: n = Node(new_str, top, num_transformations) stack.push(n) added_to_stack.append(new_str) return 0, []
def shortest_transformation(start, end, dict): assert(len(start) == len(end)) dict.append(end) root = Node(start, None, 1) stack = Stack() stack.push(root) char_list = [] for i in range(0, len(start)): char_list.append(set([word[i] for word in dict])) added_to_stack = [start] while not stack.empty(): top = stack.pop() original_str = top.data num_transformations = top.transformations + 1 for i in range(0, len(original_str)): for c in char_list[i]: new_str = original_str new_str = new_str.replace(new_str[i], c) if new_str == original_str: continue if new_str == end: # figure out the transformations transformations = [new_str] node = top while node.parent is not None: transformations.append(node.data) node = node.parent transformations.append(start) transformations.reverse() print(" --> ".join(transformations)) return num_transformations if new_str in dict: if new_str not in added_to_stack: n = Node(new_str, top, num_transformations) stack.push(n) added_to_stack.append(new_str) return 0, []
def has_valid_parens(string): stack = Stack() closing_ops = [')','}',']'] open_ops = ['(', '{', '['] open_close_dict = { '(': ')', '{': '}', '[': ']', } for c in string: if c in closing_ops: top = stack.pop() if open_close_dict[top] != c: return False elif c in open_ops: stack.push(c) return stack.empty()