“”"28. 实现strStr()
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = “hello”, needle = “ll”
输出: 2
“”"
class Solution:
#1:正则
def strStr1(self, haystack, needle) -> int:
import re
res = re.search(needle,haystack)
if res:
return res.span()[0]
else:
return -1
#2:遍历+切片
def strStr(self, haystack, needle) -> int:
length = len(needle)
for i in range(len(haystack)+1-length):
if haystack[i:i+length] == needle:
return i
return -1
#3:find方法
def strStr(self, haystack, needle) -> int:
return haystack.find(needle)
“”"35.搜索插入位置
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
假设数组中无重复元素。
示例 1:
输入: [1,3,5,6], 5
输出: 2
示例 2:
输入: [1,3,5,6], 2
输出: 1
“”"
class Solution:
#1.遍历
def searchInsert(self, nums, target) -> int:
for idx,value in enumerate(nums):
if value >= target:
return idx
return idx+1
print(Solution().searchInsert([1,3,5,6],5))
print(Solution().searchInsert([1,3,5,6],7))
print(Solution().searchInsert([1,3,5,6],2))
“”"38.报数
报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:
-
1
-
11
-
21
-
1211
-
111221
1 被读作 “one 1” (“一个一”) , 即 11。
11 被读作 “two 1s” (“两个一”), 即 21。
21 被读作 “one 2”, “one 1” (“一个二” , “一个一”) , 即 1211。
给定一个正整数 n(1 ≤ n ≤ 30),输出报数序列的第 n 项。
注意:整数顺序将表示为一个字符串。
示例 1:
输入: 1
输出: “1”
示例 2:
输入: 4
输出: “1211”
“”"
class Solution:
#1:递归计算前一个元素中不同数字的个数
def countAndSay1(self, n) -> str:
if n ==1:
return ‘1’
result = ‘’
# 前一个元素组成的字符串
previous = self.countAndSay1(n-1)
#统计相邻相同字符的个数
num = 0
#取出第1个元素
temp_value = previous[0]
for idx,value in enumerate(previous) :
#如果只有1个元素直接返回其个数和值
if len(previous)==1:
result += str(num+1)+previous[-1]
break
#如果遍历出的值和temp_value相同,个数加1
if value == temp_value:
num += 1
else:
#不相同的,将之前统计的元素个数和元素值拼接到result中
result += str(num)+temp_value
temp_value = value
num = 1
#最后一个元素
if idx == len(previous)-1:
result += str(num)+previous[-1]
return result
def countAndSay2(self, n) -> str:
if n == 1: return '1' # 递归出口
s = self.countAndSay2(n-1)
res, count = '', 0
for i in range(len(s)):
count += 1
if i == len(s) - 1 or s[i] != s[i+1]: # 最后一个字符串要提前终止
res += str(count)
res += s[i]
count = 0
return res
print(Solution().countAndSay1(8))
print(Solution().countAndSay2(8))