输入:s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"]
输出:[]
示例 3:
输入:s = "barfoofoobarthefoobarman", words = ["bar","foo","the"]
输出:[6,9,12]
提示:
1 <= s.length <= 104
s 由小写英文字母组成
1 <= words.length <= 5000
1 <= words[i].length <= 30
words[i] 由小写英文字母组成
挨个匹配:
# @lc app=leetcode.cn id=30 lang=python3
#
# [30] 串联所有单词的子串
#
# @lc code=start
class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
import copy
ls=len(s)
lw=len(words)
wordlen=len(words[0])
dicts=dict()
res=[]
for i in range(lw):
if words[i] in dicts:
dicts[words[i]]=dicts[words[i]]+1
else:
dicts[words[i]]=1
for i in range(ls-wordlen*lw+1):
new=copy.copy(dicts)
rev=1
for j in range(i,i+wordlen*lw,wordlen):
if s[j:j+wordlen] in new and new[s[j:j+wordlen]]!=0:
new[s[j:j+wordlen]]-=1
else:
rev=0
break
if rev==1:
res.append(i)
return res
# @lc code=end
# [25] K 个一组翻转链表
#
#法1 :只交换值
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
head1=head
fhead= ListNode(0,head)
head2=fhead
end=0
while head1!= None:
nums=list()
for i in range(k):
head2=head2.next
if head2==None:
end=1
break
#print(head2.val)
nums.append(head2.val)
if end==0:
for i in range(k):
head1.val=nums[k-1-i]
head1=head1.next
else:
for i in range(len(nums)):
head1.val=nums[i]
head1=head1.next
return fhead.next
# @lc code=end
# @lc app=leetcode.cn id=70 lang=python3
#
# [70] 爬楼梯
#
# @lc code=start
class Solution:
def climbStairs(self, n: int) -> int:
dp=[0 for i in range(n)]
for i in range(n):
if i == 0:
dp[0]=1
continue
if i == 1:
dp[1]=2
continue
dp[i]=dp[i-1]+dp[i-2]
return dp[n-1]
# @lc app=leetcode.cn id=64 lang=python3
#
# [64] 最小路径和
#
#动态规划 dp[i][j]时到i,j的最小路径和
# @lc code=start
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
row = len(grid)
col = len(grid[0])
dp=[[0]*col for i in range(row)]
for i in range(row):
for j in range(col):
if i == 0 and j!=0:
dp[i][j]=dp[i][j-1]+grid[i][j]
elif j == 0 and i!=0:
dp[i][j]=dp[i-1][j]+grid[i][j]
elif i==0 and j==0:
dp[i][j]=grid[0][0]
else :
dp[i][j]=min(dp[i-1][j],dp[i][j-1])+grid[i][j]
return dp[row-1][col-1]