前言
今天的题目都是简单的模拟,需要注意的只有:python中的str不能直接修改值
一、反转字符串
leetcode344 反转字符串
简单的头尾指针,原地反转字符串
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
n = len(s)
head, tail = 0, n - 1
while head < tail:
tmp = s[head]
s[head] = s[tail]
s[tail] = tmp
head += 1
tail -= 1
二、反转字符串II
class Solution:
def reverseStr(self, s: str, k: int) -> str:
t = list(s)
for i in range(0, len(t), 2 * k):
t[i: i + k] = reversed(t[i: i + k])
return "".join(t)
三、卡码54 替换数字
def exchange(str s):
result = ""
for i in range(len(s)):
if s[i] >= '0' and s[i] <= '9':
result += "number"
else:
result += "s[i]"
return result