仅以此纪录每日LeetCode所刷题目(该学习了...)。
题目描述:
示例:
代码:
class Solution:
def platesBetweenCandles(self, s: str, queries: List[List[int]]) -> List[int]:
n = len(s)
# presum: 统计*的前缀和, lefts: 统计每个坐标左边最近的|的坐标, rights: 统计每个坐标右边最近的|的坐标
presum, lefts, rights, l = [0] * (n + 1), [-1] * n, [-1] * n, -1
for i, c in enumerate(s):
if c == '*':
# 当前字符为*,前缀和个数加一
presum[i + 1] = presum[i] + 1
else:
# 当前字符为|,前缀和个数不变
presum[i + 1] = presum[i]
# 更新最新的坐标最近坐标(接下来下次更新前最近的都是i)
l = i
lefts[i] = l
# 右边与左边的更新同理,只需要从右往左
r = -1
for i, c in enumerate(s[::-1]):
if c == '|':
r = n - 1 - i
rights[n - 1 - i] = r
# 最终答案只有 左查询点的右边有蜡烛、右查询点的左边有蜡烛、且右边的蜡烛在左边的蜡烛右边中间才可能有*,否则肯定是0个
return [presum[lefts[r]] - presum[rights[l]] if rights[l] >= 0 and lefts[r] >= 0 and rights[l] < lefts[r] else 0 for l, r in queries]
题目描述:
示例:
思路:
这道题我的思路比较简单,没有用到很复杂的算法。首先我将每个数字对应的字母存储在字典中,因为这道题的要求中已经写出了给出的digits长度在0-4之间,因此我可以先判断digits的长度来判断循环的次数,之后形成字符串(后来发现这种方法太弱智了,如果digits的长度变得长一些根本就不可行)。
之后我使用了一种回溯方法,代码也放在下面了。
代码:
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
dict1 = {2:['a','b','c'],
3:['d','e','f'],
4:['g','h','i'],
5:['j','k','l'],
6:['m','n','o'],
7:['p','q','r','s'],
8:['t','u','v'],
9:['w','x','y','z']}
if len(digits) == 0:
list1 = []
return list1
if len(digits) == 1:
return dict1[int(digits)]
if len(digits) == 2:
list1 = []
for i in dict1[int(digits[0])]:
for j in dict1[int(digits[1])]:
a = i+j
list1.append(a)
return list1
if len(digits) == 3:
list1 = []
for i in dict1[int(digits[0])]:
for j in dict1[int(digits[1])]:
for k in dict1[int(digits[2])]:
a = i+j+k
list1.append(a)
return list1
if len(digits) == 4:
list1 = []
for i in dict1[int(digits[0])]:
for j in dict1[int(digits[1])]:
for k in dict1[int(digits[2])]:
for w in dict1[int(digits[-1])]:
a = i+j+k+w
list1.append(a)
return list1
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if not digits: return []
phone = {'2':['a','b','c'],
'3':['d','e','f'],
'4':['g','h','i'],
'5':['j','k','l'],
'6':['m','n','o'],
'7':['p','q','r','s'],
'8':['t','u','v'],
'9':['w','x','y','z']}
def backtrack(conbination,nextdigit):
if len(nextdigit) == 0:
res.append(conbination)
else:
for letter in phone[nextdigit[0]]:
backtrack(conbination + letter,nextdigit[1:])
res = []
backtrack('',digits)
return res