题目一:实现strStr()函数
链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnr003/
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
例1:
输入:haystack = "hello", needle = "ll"
输出:2
例2:
输入:haystack = "aaaaa", needle = "bba"
输出:-1
思路一:
根据Sunday算法实现
Sunday匹配机制如下:
目标字符串—haystack
模式串—needle
当前查询索引—index(初始为0)
待匹配字符串—str(haystack[index:index + len(needle)])
每次匹配从目标字符串中提取待匹配字符串,然后与模式串进行比较:
若相同,则返回index;
若不相同,则索取待匹配字符串后一位的字符s
s存在模式串中,则 index = index + shiftList[s],否则 index = index + len(needle)
shiftList(偏移表)计算
存储着模式串中每位字符与字符s匹配后对应index位移的量
例如:abc
a:len(needle)- 0 = 3
b:len(needle)- 1 = 2
c:len(needle)- 2 = 1
def shiftList(s):
dic = {}
l = len(s)
for i in range(l):
dic[s[i]] = l - i
dic['ot'] = l + 1
return dic
def strStr(haystack, needle):
# Sunday算法
if len(haystack) < len(needle):
return -1
if needle == haystack:
return 0
dic = shiftList(needle)
l1 = len(haystack)
l2 = len(needle)
index = 0
while index + l2 <= l1:
str_acc = haystack[index:index+l2] # 待匹配字符
if str_acc == needle:
return index
else:
if index + l2 >= l1: # 下标更新匹配后,判断是否还会超出边界
return -1
str_next = haystack[index + l2]
if dic.get(str_next):
index += dic[str_next]
else:
index += dic['ot']
return -1
思路二(暴力解法):
形成一个窗口,遍历循环目标字符串
def strStr(self, haystack, needle):
l1, l2 = len(haystack), len(needle)
for num in range(l1-l2+1):
if haystack[num:num+l2] == needle:
return num
return -1
题目二:外观数列
链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnpvdm/
给定一个正整数 n ,输出外观数列的第 n 项。
「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。
你可以将其视作是由递归公式定义的数字字符串序列:
countAndSay(1) = “1”
countAndSay(n) 是对 countAndSay(n-1) 的描述,然后转换成另一个数字字符串。
前五项如下:
-
1
-
11
-
21
-
1211
-
111221
第一项是数字 1
描述前一项,这个数是 1 即 “ 一 个 1 ”,记作 “11”
描述前一项,这个数是 11 即 “ 二 个 1 ” ,记作 “21”
描述前一项,这个数是 21 即 “ 一 个 2 + 一 个 1 ” ,记作 “1211”
描述前一项,这个数是 1211 即 “ 一 个 1 + 一 个 2 + 二 个 1 ” ,记作 “111221”
要 描述 一个数字字符串,首先要将字符串分割为 最小 数量的组,每个组都由连续的最多 相同字符 组成。然后对于每个组,先描述字符的数量,然后描述字符,形成一个描述组。要将描述转换为数字字符串,先将每组中的字符数量用数字替换,再将所有描述组连接起来。
例1:
输入:n = 1
输出:"1"
解释:这是一个基本样例。
例2:
输入:n = 4
输出:"1211"
解释:
countAndSay(1) = "1"
countAndSay(2) = 读 "1" = 一 个 1 = "11"
countAndSay(3) = 读 "11" = 二 个 1 = "21"
countAndSay(4) = 读 "21" = 一 个 2 + 一 个 1 = "12" + "11" = "1211"
思路:
运用递归和双指针
双指针----计算字符串中每位数字的个数
def countAndSay(self, n):
if n == 1:
return '1'
s = self.countAndSay(n-1)
slow, fast = 0, 0
num = ''
while slow < len(s):
while fast < len(s) and s[slow] == s[fast]:
fast += 1
num += str(fast-slow) + s[slow]
slow = fast
return num