一、括号匹配问题
输入包含中括号,圆括号和大括号,判断,括号是否合理
输入:
s1 = "{[()]}({[]})"
s2 = "{{{[[((])))]]]}}}"
s3 = ")()({}"
输出:
Yes
No
No
思路:采用栈的逻辑,遇到左括号入栈,遇到右括号则判断是否能够匹配的哦对应的额左括号,如果匹配上了,就将匹配的括号出栈,否则输出No,如果全部匹配完成,最终栈为空,则输出Yes
d = {")": "(",
"]": "[",
"}": "{"}def brackets(s):
l = []
for i in s:
if i in ['(', '[', '{']:
l.append(i)
# print(l)
elif l and l.pop() != d[i]:
print(l)
print("No")
break
elif not l:
print("No")
return
if not l:
print('Yes')
二、数字交换
输入一个整数,通过最多交换两个位置的数字,得到最大输出
num1 = 326587 # 826537
num2 = 99191919 # 99991911
num3 = 1992 # 9912
num4 = 9128 # 9912
思路一:暴力搜索
def swap(l, i, j):
temp = l[i]
l[i] = l[j]
l[j] = temp
return int("".join(l))l = list(str(num1))
res = 0
for i in range(len(l)-1):
for j in range(i+1, len(l)):
if l[i] < l[j]:
swap_data = swap(l, i, j)
res = max(swap_data, res)
l = list(str(swap(l, i, j)))
print(res)
思路二:
step1. 找到最大的数字及其位置,如果最大数字不出现在首位,则记录最低位置的最大数,将最大数与首位交换
step2. 如果最大数字出现在首位,则将其去掉,重复step1操作
m = max(l)
l_copy = l.copy()
l_copy.reverse()
ind = len(l)-l_copy.index(m)-1for i in range(len(l)-1):
if l[i]<m and i<ind and ind > i:
res = swap(l, i, ind)
print(res)
break
else:
m = max(l[i+1:])
l_copy = l.copy()
l_copy.reverse()
ind = len(l)-l_copy.index(m)-1