题目一
class Solution(object):
def reverseString(self, s):
"""
:type s: List[str]
:rtype: None Do not return anything, modify s in-place instead.
"""
right=len(s)-1
left=0
while left<=right:
n=s[left]
s[left]=s[right]
s[right]=n
left+=1
right-=1
题目二
class Solution(object):
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
s=list(s)
index=0
while index<len(s)-1:
left=index
if (len(s)-1)-index<k:
right=len(s)-1
else:
right=index+k-1
while left<=right:
n=s[left]
s[left]=s[right]
s[right]=n
left+=1
right-=1
index=index+2*k
string=''
for i in s:
string+=i
return string
题目三:
class Solution:
def change(self, s):
new_s=''
# Python里面的string也是不可改的,所以也是需要额外空间的。空间复杂度:O(n)。
for i in s:
if i.isdigit():
i = "number"
new_s+=i
return new_s
class Solution:
def change(self, s):
ls=list(s)
p1=len(ls)-1
count=0
# Python里面的string也是不可改的,所以也是需要额外空间的。空间复杂度:O(n)。
for i in range(len(ls)):
if ls[i].isdigit():
count+=1
ls+='0'*count*5
p2=len(ls)-1
while p1>=0:
if ls[p1].isdigit():
ls[p2]='r'
ls[p2-1] = 'e'
ls[p2-2] = 'b'
ls[p2-3] = 'm'
ls[p2-4] = 'u'
ls[p2-5] = 'n'
p2-=6
else:
ls[p2]=ls[p1]
p2-=1
p1-=1
return ''.join(ls)
题目四
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
s=s.split()
left,right=0,len(s)-1
while left<=right:
temp=s[left]
s[left]=s[right]
s[right]=temp
left+=1
right-=1
return ' '.join(s)
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
s=s.strip()
s=s[::-1]
s_new=[]
for word in s.split():
w=word[::-1]
s_new.append(w)
return ' '.join(s_new)
题目五
#获取输入的数字k和字符串
k = int(input())
s = input()
#通过切片反转第一段和第二段字符串
#注意:python中字符串是不可变的,所以也需要额外空间
s = s[len(s)-k:] + s[:len(s)-k]
print(s)