原题
Given a string S, return the “reversed” string where all characters that are not a letter stay in the same place, and all letters reverse their positions.
Example 1:
Input: “ab-cd”
Output: “dc-ba”
Example 2:
Input: “a-bC-dEf-ghIj”
Output: “j-Ih-gfE-dCba”
Example 3:
Input: “Test1ng-Leet=code-Q!”
Output: “Qedo1ct-eeLg=ntse-T!”
Note:
S.length <= 100
33 <= S[i].ASCIIcode <= 122
S doesn’t contain \ or "
解法1
先将S中的字母放入列表ans里, 然后记录S中非字母的索引和字符, 再遍历non_letters, 将非字母的字符插入ans中, 最后将ans转化为字符串.
Time: 3*O(n)
Space: O(1)
代码
class Solution(object):
def reverseOnlyLetters(self, S):
"""
:type S: str
:rtype: str
"""
ans = [char for char in S if char.isalpha()][::-1]
# get the index and char of non-letters
non_letters = [(i, char) for i, char in enumerate(S) if not char.isalpha()]
for i, char in non_letters:
ans.insert(i, char)
return ''.join(ans)
解法2
双指针法, 定义左右两个指针, 从左右两边往中间刷, 遇到字母时, 两个字母交换.
Time: O(n)
Space: O(1)
代码
class Solution(object):
def reverseOnlyLetters(self, S):
"""
:type S: str
:rtype: str
"""
l, r = 0, len(S)-1
s = list(S)
while l < r:
while l < r and not S[l].isalpha():
l += 1
while l < r and not S[r].isalpha():
r -= 1
# swap two letters
s[l], s[r] = s[r], s[l]
l += 1
r -= 1
return ''.join(s)