344 反转字符串
解题思路
就像反转链表,使用双指针
class Solution(object):
def reverseString(self, s):
"""
:type s: List[str]
:rtype: None Do not return anything, modify s in-place instead.
"""
small=0
max=len(s)-1
while small<max:
s[small],s[max]=s[max],s[small]
small+=1
max-=1
if __name__=="__main__":
s = ["h", "e", "l", "l", "o"]
solu=Solution()
solu.reverseString(s)
print(s)
541 反转字符串II
解题思路
其实和第一题大同小异,主要是考虑cur的变化
class Solution(object):
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
def rever(s,cur,k):
small=cur
max=k
while small<max:
s[small],s[max]=s[max],s[small]
small+=1
max-=1
s_list=list(s)
lenth=len(s_list)
cur=0
while cur+2*k<=lenth:
rever(s_list,cur,cur+k-1)
cur=cur+2*k
if cur+2*k>lenth:
if lenth-cur>k:
rever(s_list,cur,cur+k-1)
else:
rever(s_list,cur,lenth-1)
s=''.join(s_list)
return s
if __name__=="__main__":
s="abcdefg"
k=1
solu=Solution()
print(solu.reverseStr(s,k))
# 输出:"bacdfeg"
05 替换空格
解题思路
string 不能修改值,但是list可以,把string改为list即可
class Solution(object):
def replaceSpace(self, s):
"""
:type s: str
:rtype: str
"""
s_list=list(s)
i=0
while i < len(s_list):
if s_list[i] ==" ":
s_list[i]="%20"
i+=1
s="".join(s_list)
return s
if __name__=="__main__":
# 输入:s = "We are happy."
# 输出:"We%20are%20happy."
s = "We are happy."
solu=Solution()
print(solu.replaceSpace(s))
151 翻转字符串里的单词
解题思路
先将空格去掉,然后将+整个反转,再将单词反转,注意还要去掉单词中间的空格
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
def reverse(s,small,max):
while small < max:
s_list[small], s_list[max] = s_list[max], s_list[small]
small += 1
max -= 1
start=0
end=len(s)-1
s_list=list(s)
# 去除空格
while s_list[start]==" ":
start+=1
while s_list[end]==" ":
end-=1
# 反转
small=start
max=end
reverse(s_list,small,max)
# 反转单词
cur=start
next=cur
while next!=end:
if s_list[next]==" ":
reverse(s_list,cur,next-1)
if next+1<end and s_list[next+1]==" ":
next+=1
while s_list[next]==" ":
s_list.pop(next)
end-=1
if s_list[next]!=" ":
cur=next
else:
cur=next+1
next=cur
else:
next+=1
if next==end:
reverse(s_list, cur, next)
s="".join(s_list[start:end+1])
return s
if __name__=="__main__":
solu=Solution()
s = "example good a"
print(solu.reverseWords(s))
58-II左旋转字符串
解题思路
找到开始交换的那个节点,然后将两个字符串拼起来即可
class Solution(object):
def reverseLeftWords(self, s, n):
"""
:type s: str
:type n: int
:rtype: str
"""
# b=list("umgh")
# a=list("lrlose")
# print("".join(b+a))
s_list=list(s)
start=n
a=[]
while start<len(s_list):
a.append(s_list[start])
start+=1
s="".join(a+s_list[0:n])
return s
if __name__=="__main__":
# 输入: s = "lrloseumgh", k = 6
# 输出: "umghlrlose"
s="lrloseumgh"
k=6
solu=Solution()
solu.reverseLeftWords(s,k)