Q:
给定一个字符串 S
,返回 “反转后的” 字符串,其中不是字母的字符都保留在原地,而所有字母的位置发生反转。
示例 1:
输入:"ab-cd"
输出:"dc-ba"
示例 2:
输入:"a-bC-dEf-ghIj"
输出:"j-Ih-gfE-dCba"
思路:双指针,分别从字符串两侧向中间遍历,判断是否是字母,如果是,交换两个字符
class Solution:
def reverseOnlyLetters(self, S):
"""
:type S: str
:rtype: str
"""
temp = [i for i in S]
left = 0
right = len(temp)-1
while(left < right):
if self.isword(temp[left]):
if self.isword(temp[right]):
temp[left],temp[right] = temp[right],temp[left]
left += 1
right -= 1
else:
right-=1
else:
left+=1
return (''.join(temp))
def isword(self,w):
if ord(w) >= ord('a') and ord(w) <= ord('z') or (ord(w) >= ord('A') and ord(w) <= ord('Z')):
return True
else:
return False
使用内置函数 isalpha() 发现效率并不是很好,代码如下:
class Solution:
def reverseOnlyLetters(self, S):
"""
:type S: str
:rtype: str
"""
temp = [i for i in S]
left = 0
right = len(temp)-1
while(left < right):
if temp[left].isalpha():
if temp[right].isalpha():
temp[left],temp[right] = temp[right],temp[left]
left += 1
right -= 1
else:
right-=1
else:
left+=1
return (''.join(temp))