昨天的leetcode考试,因为坐车的原因,没有参加。这里补一下。
第一题
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 "
题意很明显,给你一个字符串,只把字母部分的进行reverse. 其他部分的字符保持不变。
这个题貌似很简单,但是需要注意边界问题。 例如只有一个字符的时候,全部都是非字母的情况。 这些情况都需要考虑进去。
class Solution(object):
def reverseOnlyLetters(self, S):
"""
:type S: str
:rtype: str
"""
a = 0
b = len(S) - 1
if b == 0:
return S
ret = [0] * len(S)
while a <= b:
while not S[a].isalpha() and a < b:
ret[a] = S[a]
a += 1
while not S[b].isalpha() and a < b:
ret[b] = S[b]
b -= 1
ret[a], ret[b] = S[b], S[a]
a += 1
b -= 1
return "".join([str(i) for i in ret])