题目一:
题目链接: https://leetcode-cn.com/problems/consecutive-characters/
解题思路:
从第二个字符开始遍历,当前长度和最大长度初始化为1
如果遍历到的字符,和上个字符相同,则当前长度 += 1,最大长度 = max(最大长度,当前长度)
如果和上个字符不相同,则重置当前长度 = 1,继续遍历
代码实现:
class Solution:
def maxPower(self, s: str) -> int:
max_len = 1
last_cha = s[0]
curr_len = 1
for idx in range(1, len(s)):
if s[idx] == last_cha:
curr_len += 1
max_len = max(max_len, curr_len)
else:
curr_len = 1
last_cha = s[idx]
return max_len
题目二:
题目链接: https://leetcode-cn.com/problems/simplified-fractions/
解题思路:
两层循环,第一层为分母,第二层为分子
判断是否将当前结果加入结果集时,计算分子和分母之间的公约数是否是1。如果是1,则加入;如果不是1,则忽略
代码实现:
class Solution:
def simplifiedFractions(self, n: int) -> List[str]:
res = []
for down in range(2, n + 1):
res.append("1/" + str(down))
for up in range(2, down):
if 1 == math.gcd(down, up): res.append(str(up) + "/" + str(down))
return res
题目三:
题目链接: https://leetcode-cn.com/problems/count-good-nodes-in-binary-tree/
解题思路:
DFS,维护一个当前DFS的路径,或者一个当前路径的最大值
代码实现:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def goodNodes(self, root: TreeNode) -> int:
def judge_help(root, path, res):
if not root: return res
if 1 < len(path) and root.val >= max(path): res += 1
path.append(root.val)
if root.left: res = judge_help(root.left, path, res)
if root.right: res = judge_help(root.right, path, res)
path.pop()
return res
return judge_help(root, [root.val], 1)
题目四:
题目链接: https://leetcode-cn.com/problems/form-largest-integer-with-digits-that-add-up-to-target/
解题思路:
经典的DP完全背包问题,自己写的代码太长了,复制个大佬的DP
代码实现:
class Solution:
def largestNumber(self, cost: List[int], target: int) -> str:
dp = [''] + [None] * target
for i in range(1, len(cost) + 1):
for v in range(cost[i - 1], target + 1):
if dp[v - cost[i - 1]] is not None:
newval = str(i) + dp[v - cost[i - 1]]
if dp[v] is None or int(newval) > int(dp[v]):
dp[v] = newval
return '0' if dp[target] is None else dp[target]
作者:suibianfahui
链接:https://leetcode-cn.com/problems/form-largest-integer-with-digits-that-add-up-to-target/solution/di-26-chang-shuang-zhou-sai-ti-jie-by-suibianfah-3/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。