代码随想录算法训练营第二十天 | 字符串 | 反转字符串、替换空格、翻转字符串里的单词(很多基础方法)和左旋转字符串
反转字符串
【题目简介】
【解法】
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
temp = ""
mid = len(s) // 2
for i in range(mid):
temp = s[len(s) - 1 - i]
s[len(s) - 1 - i] = s[i]
s[i] = temp
print(s)
- 如果for循环中mid写成mid+1就不行了!
替换数字
【题目简介】
【解法】
class Solution(object):
def subsitute_numbers(self, s):
"""
:type s: str
:rtype: str
"""
### 可能的难题:
### 1. 如果字符串以字符列表的形式展开,那么一个for循环正向遍历就可以了
### 2. 如果是以字符串的形式解题,字符串本身又不能修改......
count = sum(1 for char in s if char.isdigit()) # 统计数字的个数
expand_len = len(s) + (count * 5) # 计算扩充后字符串的大小, x->number, 每有一个数字就要增加五个长度
res = [''] * expand_len
new_index = expand_len - 1 # 指向扩充后字符串末尾
old_index = len(s) - 1 # 指向原字符串末尾
while old_index >= 0: # 从后往前, 遇到数字替换成“number”
if s[old_index].isdigit():
# 如果expand = 11 则new_index = 10
# res[5: 11] 正好能承载6位字符!
res[new_index-5:new_index+1] = "number"
new_index -= 6
else:
res[new_index] = s[old_index]
new_index -= 1
old_index -= 1
return "".join(res)
def subsitute_numbers2(self, s):
"""
:type s: str
:rtype: str
"""
### 可能的难题:
### 1. 如果字符串以字符列表的形式展开,那么一个for循环正向遍历就可以了
### 2. 如果是以字符串的形式解题,字符串本身又不能修改......
s_lst = list(s)
for i in range(len(s)):
if s[i].isdigit():
s_lst[i] = "number"
return "".join(s_lst)
if __name__ == "__main__":
solution = Solution()
while True:
try:
s = input()
result = solution.subsitute_numbers2(s)
print(result)
except EOFError:
break
- 本题如果使用python可以偷懒
- 本题重在应用双指针的方法进行数字替换!
翻转字符串里的单词
【题目简介】
【解法1】
class Solution:
def reverseWords(self, s: str) -> str:
# 1. 先将单词添加到列表中
# 2. 翻转列表
# 3. 使用空格作为分隔符构建成结果
s = list(s)
words = []
word = ""
for i in range(len(s)):
#### 最为重要的一点!
#### 默认遇到空格,默认前面就是一个单词
if s[i] == " ":
if len(word) != 0:
words.append(word)
word = ""
else:
word += s[i]
### 处理最后一个以单词结尾的字符串
if i == len(s) - 1:
words.append(word)
word = ""
words.reverse()
print(words)
return " ".join(words)
- 其实这道题可以通过很多方式实现;
左旋转字符串
【题目简介】
【解法】
k = int(input())
s = input()
print(s[-k:] + s[:-k])