反转字符串,
def reverseStr541(s, k):
def reverseString344(s):
sm = ''
for i in range(len(s)-1,-1,-1):
sm = sm+s[i]
return sm
i = 0
sm=''
while(i
自己的思路,先按照空格分割字符串,然后从后到先加一下就行,52ms
def reverseWords15102(s):
res = ""
all=[]
for i in s:
if i!=" ":
res=res+i
else:
if len(res)>0:
all.append(res)
res=""
if len(res) > 0:
all.append(res)
res = ""
for i in range(len(all)-1,0,-1):
res = res+all[i]+" "
res = res+all[0]
print(res)
leetcode的题解,还是牛,先split(),就直接按空格划分了,前后的空格也没了,然后反转一下,超快,40ms
def reverseWords15103(s):
return " ".join(reversed(s.split()))
一道暴力匹配的简单题,但kmp
def strStr28(haystack, needle):
for i in range(len(haystack)):
if haystack[i]==needle[0]:
j=1
while(j
暴力匹配
def repeatedSubstringPattern459(s):
for i in range(1,len(s)):
tmp = s[:i]
j=i
while(j
其实中间有很多队栈的,都跳过了,不想搞,,。
def evalRPN150(tokens):
res=[]
s = ["+","-","*" , "/"]
for i in tokens:
if i in s:
b = res.pop()
a = res.pop()
if i=="+":
sum = a+b
elif i=="-":
sum = a-b
elif i=="*":
sum = a*b
else:
sum = int(a/b)
res.append(sum)
else:
res.append(int(i))
return res[0]
暴力肯定超时,关键是如何记录前面的,看了思路单调栈从大到小的小标,,记录前面的最大值的下标,以及最大值后面的第二最大值,
1、新来的值,从后往前比,比它小的都pop,直到遇到比它大的停止
2、最大值是否出界,从前往后比,超出范围的都pop,剩下的栈里面都一个值就是最大值
但是用 collections.deque() 会快很多
def maxSlidingWindow23902(nums, k):
q = []
for i in range(k):
while len(q)!=0 and nums[i]>nums[q[-1]]:
q.pop()
q.append(i)
all= [nums[q[0]]]
for i in range(k,len(nums)):
while len(q) != 0 and nums[i] > nums[q[-1]]:
q.pop()
q.append(i)
while q[0]<=i-k:
q = q[1:]
all.append(nums[q[0]])
return all
单调栈,python就用的字典,关键是对字典排序,最初想的是再插入的时候就排序,因为套了三层循环,就特别慢
def topKFrequent347(nums, k):
arr = []
for i in range(len(nums)):
tmp = nums[i]
f = 0
for j in range(len(arr)-1,-1,-1):
if tmp==arr[j][0]:
f=1
arr[j][1] = arr[j][1]+1
while(j>0):
if arr[j-1][1]
发现还是遍历完之后,再sort排序,要快很多,把字典转换为list,排序
def topKFrequent34702(nums, k):
arr = {}
for i in range(len(nums)):
tmp = nums[i]
if tmp in arr:
arr[tmp] = arr[tmp]+1
else:
arr[tmp] = 1
tuple1 = zip(arr.values(), arr.keys())
#arr= sorted(arr.items(),key=lambda x:x[1])
arr = sorted(tuple1,reverse=True)
print(arr)
res = []
for i in arr:
if len(res)==k:
break
res.append(i[1])
return res
唉,用python就是对数据结构不太弄的明白,,就这样把。