class Solution: def isValid(self, s: str) -> bool: if (len(s)%2==1): returnFalse
flagStack=[] pair={')':'(','}':'{',']':'['} forchar in s: if len(flagStack)!=0: ifchar in pair and flagStack[-1]==pair[char]: flagStack.pop() else: flagStack.append(char) else: flagStack.append(char)
class Solution: def decodeString(self, s: str) -> str: elementStack=[] temp='' num='' forchar in s: elementStack.append(char) ifchar==']': # 提取字符串 elementStack.pop() while(elementStack[-1]!='['): top=elementStack.pop() temp+=top[::-1] elementStack.pop() while(len(elementStack)>0 and elementStack[-1].isdigit()): num+=elementStack.pop() # 新的字符 for i in range(int(num[::-1])): elementStack.append(temp[::-1]) num='' temp='' res='' for e in elementStack: res+=e return res
class Solution: def nextGreaterElements(self, nums: List[int]) -> List[int]: res=[] stack=[] temp=[-1for _ in range(len(nums))] stack_index=[] for i in range(len(nums)*2): while stack and nums[i%len(nums)]>stack[-1]: index=stack_index.pop() stack.pop() temp[index]=nums[i%len(nums)] stack_index.append(i%len(nums)) stack.append(nums[i%len(nums)]) return temp
classSolution: def dailyTemperatures(temperatures): # 因为等价于找第i元素后,高于这个元素的index之差 # 可以考虑使用一个stack来记录递减元素的下标 size=len(temperatures) ans=[0for _ in range(size)] stack=[] for i in range(size): while( stack and temperatures[i]>temperatures[stack[-1]]): index=stack.pop() ans[index]=i-index stack.append(i) return ans
forcharin s: ifchar not in resStack: # 如果不在resStack中,我需要设置一个尽可能小的序列 # 同时需要保证还有数 while resStack and char<resStack[-1] and charMap[resStack[-1]]>0: resStack.pop() resStack.append(char) charMap[char]-=1 else: charMap[char]-=1 return''.join(resStack)
class Solution: def findUnsortedSubarray(self, nums: List[int]) -> int: # 如果必然存在这样的一个数组,那么肯定是单调递增,然后***、然后单调递增 # 从小到大,找到左边界 iflen(nums)<2: return0 stack=[] size=len(nums) left=size-1 right=0 for i in range(size): while(stack and nums[i]<nums[stack[-1]]): left=min(left,stack.pop()) stack.append(i) stack[:]=[] for i in range(size-1,-1,-1): while(stack and nums[i]>nums[stack[-1]]): right=max(right,stack.pop()) stack.append(i)