目录
1、最短回文串(字符串匹配)
给定一个字符串 s,你可以通过在字符串前面添加字符将其转换为回文串。找到并返回可以用这种方式转换的最短回文串。
示例 1:
输入:s = "aacecaaa"
输出:"aaacecaaa"
示例 2:
输入:s = "abcd"
输出:"dcbabcd"
提示:
- 0 <= s.length <= 5 * 104
- s 仅由小写英文字母组成
选项代码:
class Solution:
def shortestPalindrome(self, s: str) -> str:
N = len(s)
idx1 = 0
for idx2 in range(N - 1, -1, -1):
if s[idx1] == s[idx2]:
idx1 += 1
if idx1 == N:
return s
return s[idx1:][::-1] + self.shortestPalindrome(s[:idx1]) + s[idx1:]
# %%
s = Solution()
print(s.shortestPalindrome(s = "abcd"))
2、二叉树展开为链表(栈、树)
给你二叉树的根结点 root ,请你将它展开为一个单链表:
- 展开后的单链表应该同样使用 TreeNode ,其中 right 子指针指向链表中下一个结点,而左子指针始终为 null 。
- 展开后的单链表应该与二叉树 先序遍历(https://baike.baidu.com/item/%E5%85%88%E5%BA%8F%E9%81%8D%E5%8E%86/6442839?fr=aladdin) 顺序相同。
示例 1:
输入:root = [1,2,5,3,4,null,6]
输出:[1,null,2,null,3,null,4,null,5,null,6]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [0]
输出:[0]
提示:
- 树中结点数在范围 [0, 2000] 内
- -100 <= Node.val <= 100
进阶:你可以使用原地算法(O(1) 额外空间)展开这棵树吗?
选项代码:
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
while root != None:
if root.left == None:
root = root.right
else:
pre = root.left
while pre.right != None:
pre = pre.right
pre.right = root.right
root.right = root.left
root.left = None
root = root.right
3、解码方法(字符串,动态规划)
一条包含字母 A-Z 的消息通过以下映射进行了 编码 :
'A' -> 1'B' -> 2...'Z' -> 26
要 解码 已编码的消息,所有数字必须基于上述映射的方法,反向映射回字母(可能有多种方法)。例如,"11106" 可以映射为:
- "AAJF" ,将消息分组为 (1 1 10 6)
- "KJF" ,将消息分组为 (11 10 6)
注意,消息不能分组为 (1 11 06) ,因为 "06" 不能映射为 "F" ,这是由于 "6" 和 "06" 在映射中并不等价。
给你一个只含数字的 非空 字符串 s ,请计算并返回 解码 方法的 总数 。
题目数据保证答案肯定是一个 32 位 的整数。
示例 1:
输入:s = "12"
输出:2
解释:它可以解码为 "AB"(1 2)或者 "L"(12)。
示例 2:
输入:s = "226"
输出:3
解释:它可以解码为 "BZ" (2 26), "VF" (22 6), 或者 "BBF" (2 2 6) 。
示例 3:
输入:s = "0"
输出:0
解释:没有字符映射到以 0 开头的数字。含有 0 的有效映射是 'J' -> "10" 和 'T'-> "20" 。由于没有字符,因此没有有效的方法对此进行解码,因为所有数字都需要映射。
示例 4:
输入:s = "06"
输出:0
解释:"06" 不能映射到 "F" ,因为字符串含有前导 0("6" 和 "06" 在映射中并不等价)。
提示:
- 1 <= s.length <= 100
- s 只包含数字,并且可能包含前导零。
选项代码:
class Solution(object):
def numDecodings(self, s):
"""
:type s: str
:rtype: int
"""
ls = len(s)
if ls == 0:
return 0
dp = [0] * ls
for index in range(ls):
if index >= 1 and int(s[index - 1:index + 1]) < 27 and int(s[index - 1:index + 1]) >= 10:
if index == 1:
dp[index] = 1
else:
dp[index] += dp[index - 2]
if int(s[index]) != 0:
if index == 0:
dp[index] = 1
else:
dp[index] += dp[index - 1]
return dp[ls - 1]
# %%
s = Solution()
print(s.numDecodings(s = "226"))