344 reverse string
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
left, right = 0, len(s)-1
while left < right:
s[left], s[right] = s[right], s[left] # reverse string in place
left += 1
right -= 1
541 操作反转字符串,都先用list操作,然后转化为string
class Solution:
def reverseStr(self, s: str, k: int) -> str:
#here text is a list, we use join to transfer list to string
def reverse_substring(text):
left, right = 0, len(text) - 1
while left < right:
text[left], text[right] = text[right], text[left]
left += 1
right -= 1
return text
res = list(s)
for cur in range(0, len(s), 2*k):
res[cur: cur + k] = reverse_substring(res[cur: cur + k])
return ''.join(res) # 把res返回成字符串,''里面代表用什么连接,这里什么连接符都没有。
151:
class Solution:
def reverseWords(self, s: str) -> str:
s_list = [i for i in s.split(" ") if len(i)>0] # 如果没有长度大于零的判断,将会返回空字符,长度为0.
return " ".join(s_list[::-1]) # 将得到的字符反过来,用空格相连,并转化为字符串。
左旋转字符串:
注意往后加要一个一个索引,一个一个加,直接切片,是作为一个list整体加进去的,这样join不了。
class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
s_list =[i for i in s]
list1 = s_list[n :]
for i in range(n):
list1.append(s_list[i])
print(list1)
return ''.join(list1)