423 · valid parenthesis sequence
Given a sequence of parentheses represented by a string, it contains the following characters: '(', ')', '{', '}', '[' and ']' to determine whether it is a valid sequence of parentheses.
Brackets must be expressed in the order of '()', '() [] {}' is a valid bracket, but '([)]' is an invalid bracket.
def isValidParentheses(self, s): # write your code here if not s: return True stack = [] for i in s: if i == '(' or i == '[' or i == '{': stack.append(i) else: if not stack: return False ele = stack.pop() if (i == ')' and ele == '(') or (i == ']' and ele == '[') or (i == '}' and ele == '{'): continue else: return False return not stack
492 · queue maintenance
Implement the queue according to the linked list. The following basic methods are supported:
enqueue(item). Put the new element in the queue.
dequeue(). Remove the first element from the queue and return it.
I read what I wrote before and changed it
class MyQueue: """ @param: item: An integer @return: nothing """ def __init__(self): self.queue = None def enqueue(self, item): # write your code here if not self.queue: self.queue = ListNode(item) self.dummy = ListNode(-1, self.queue) else: self.queue.next = ListNode(item) self.queue = self.queue.next """ @return: An integer """ def dequeue(self): # write your code here print(self.dummy.next.val) res = self.dummy.next.val self.dummy = self.dummy.next return res
Here's what I wrote before:
class MyQueue: """ @param: item: An integer @return: nothing """ def __init__(self): self.beforehead = self.tail = ListNode(-1) def enqueue(self, item): # write your code here self.tail.next = ListNode(item) self.tail = self.tail.next """ @return: An integer """ def dequeue(self): # write your code here if self.beforehead.next is None: return -1 head_val = self.beforehead.next.val self.beforehead = self.beforehead.next return head_val
541 · left-handed right-handed iterator II
Similar to the topic left-handed and right-handed iterators, in this topic, you will get a list vecs, including k one-dimensional vectors.
Your task is to return the elements in the vector one by one through the next function, and iterate in the order of vecs[0][0], vecs[1][0]... vecs[k - 1][0], vecs[0][1], vecs[1][1]... vecs[k - 1][1], vecs[0][2], vecs[1][2]... vecs[k - 1][2].
Didn't write it out.
from collections import deque class ZigzagIterator2: """ @param: vecs: a list of 1d vectors """ def __init__(self, vecs): # do intialization if necessary max_col = max([len(vec) for vec in vecs]) self.queue = deque() for j in range(max_col): for i in range(len(vecs)): try: self.queue.append(vecs[i][j]) except IndexError: pass """ @return: An integer """ def _next(self): # write your code here self.queue.popleft() """ @return: True if has next """ def hasNext(self): # write your code here if self.queue: return True # Your ZigzagIterator2 object will be instantiated and called as such: # solution, result = ZigzagIterator2(vecs), [] # while solution.hasNext(): result.append(solution.next()) # Output result
After reading what I wrote before, I really forgot
import collections class ZigzagIterator2: """ @param: vecs: a list of 1d vectors """ def __init__(self, vecs): # do intialization if necessary self.queue = collections.deque() for vec in vecs: if len(vec) > 0: self.queue.append([iter(vec), len(vec)]) """ @return: An integer """ def _next(self): # write your code here vec_iter, vec_len = self.queue.popleft() value = next(vec_iter) vec_len -= 1 if vec_len > 0: self.queue.append([vec_iter, vec_len]) return value """ @return: True if has next """ def hasNext(self): # write your code here if self.queue: return True # Your ZigzagIterator2 object will be instantiated and called as such: # solution, result = ZigzagIterator2(vecs), [] # while solution.hasNext(): result.append(solution.next()) # Output result
421 · simplified path
Given the absolute path of a file (UNIX style), please simplify the path.
In Unix Indicates the current directory,... Indicates the parent directory.
The result must start with /, and there is only one /, between the two directory names. / cannot appear after the last directory name (if any). You need to ensure that the result is the shortest string that correctly represents the path.
There is one problem:
class Solution: """ @param path: the original path @return: the simplified path """ def simplify_path(self, path: str) -> str: # write your code here stack = [] li = path.split('/') for i in li: if i.isalnum(): stack.append(i) elif i == ".": continue elif i == "..": if stack: stack.pop() return "/" + "/".join(stack)
Here are the official answers:
def simplifyPath(self, path): path = path.split('/') stack = [] for i in path: if i == '..': if len(stack): stack.pop() elif i != '.' and i != '': stack.append(i) return '/' + '/'.join(stack)
According to the answer, the following code is changed:
def simplify_path(self, path: str) -> str: # write your code here stack = [] li = path.split('/') for i in li: if i == "..": if stack: stack.pop() elif i != "." and i != "": stack.append(i) return '/' + '/'.join(stack)
575 · string decoding
Give an expression s that includes numbers, letters, and square brackets. The number before the square brackets indicates the number of repetitions of the contents of the square brackets (the contents in the brackets can be a string or another expression). Please expand this expression into a string.
can't. Just look at what you wrote before.
Here's what I wrote before. It took me a long time to remember how to do it.
def expressionExpand(self, s): # write your code here stack = [] number = 0 for ch in s: if ch.isdigit(): number = number * 10 + int(ch) elif ch == '[': stack.append(number) number = 0 elif ch == ']': strs = [] while stack and not isinstance(stack[-1], int): strs.append(stack.pop()) strs.reverse() repeat = stack.pop() for _ in range(repeat): stack.append("".join(strs)) else: stack.append(ch) strs = [] while stack: strs.append(stack.pop()) strs.reverse() return ''.join(strs)
I wrote it myself again. Learned the method isinstance
def expressionExpand(self, s): # write your code here stack = [] number = 0 for ch in s: if ch.isdigit(): number = number * 10 + int(ch) elif ch == '[': stack.append(number) number = 0 elif ch == ']': strs = [] while stack and not isinstance(stack[-1], int): strs.append(stack.pop()) strs.reverse() repeat = stack.pop() for _ in range(repeat): stack.append(''.join(strs)) else: stack.append(ch) ss = [] while stack: ss.append(stack.pop()) ss.reverse() return ''.join(ss)