344. 反转字符串 - 力扣(LeetCode)
方法一
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
left = 0
right = len(s)-1
while left < right:
temp = s[left]
s[left] = s[right]
s[right] = temp
left += 1
right -= 1
return s
方法二
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
n = len(s)
for i in range(n//2):
s[i], s[n-i-1] = s[n-i-1], s[i]
方法三
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s[:] = s[::-1]
- 刷题的时候不要图方便,理解库函数是怎么运作再用
541. 反转字符串 II - 力扣(LeetCode)
class Solution(object):
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
def reverseString(s):
"""
Do not return anything, modify s in-place instead.
"""
left = 0
right = len(s)-1
while left < right:
temp = s[left]
s[left] = s[right]
s[right] = temp #可以不用中间值,可以写在一行
left += 1
right -= 1
return s
s = list(s)
n = len(s)
for i in range(0, n, 2*k):
if n-i >= k:
s[i:i+k] = reverseString(s[i:i+k]) #可以只写这一步,因为切片就算取不到i+k也会返回到最后一位
else:
s[i:n] = reverseString(s[i:n])
return ''.join(s)
54.替换数字 题目页面 (kamacoder.com)
方法一,用字典记录数字,然后遍历字符串,在字典里就用number替换
s = input()
dict = {}
for x in range(10):
dict[str(x)] = 0
s = list(s)
for i in range(len(s)):
if s[i] in dict:
s[i] = 'number'
s = ''.join(s)
print(s)
- 这题要回过头再看一遍
151. 反转字符串中的单词 - 力扣(LeetCode)
- python str不可变,空间复杂度不能是O(n)
- 暂时用最方便的做法
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
s = s.split()
s = ' '.join([word for word in s[::-1]])
return s
55 右转字符串 题目页面 (kamacoder.com)
解题思路
和上一题一样,看作k个单词,先反转整个字符串,然后反转单词
k =int(input()) #这里要换成int型,不然会报错
s =input()
s = list(s)
s = s[::-1]
s[0:k] = s[0:k][::-1]
s[k:len(s)] = s[k:len(s)][::-1]
s = ''.join(s)
print(s)