Skip to content

Latest commit

 

History

History
74 lines (51 loc) · 1.77 KB

917-reverse-only-letters.md

File metadata and controls

74 lines (51 loc) · 1.77 KB

917. Reverse Only Letters - 仅仅反转字母

给定一个字符串 S,返回 “反转后的” 字符串,其中不是字母的字符都保留在原地,而所有字母的位置发生反转。

 

示例 1:

输入:"ab-cd"
输出:"dc-ba"

示例 2:

输入:"a-bC-dEf-ghIj"
输出:"j-Ih-gfE-dCba"

示例 3:

输入:"Test1ng-Leet=code-Q!"
输出:"Qedo1ct-eeLg=ntse-T!"

 

提示:

  1. S.length <= 100
  2. 33 <= S[i].ASCIIcode <= 122 
  3. S 中不包含 \ or "

题目标签:String

题目链接:LeetCode / LeetCode中国

题解

Language Runtime Memory
python3 36 ms N/A
class Solution:
    def reverseOnlyLetters(self, S):
        """
        :type S: str
        :rtype: str
        """
        t = list(S)
        i, j = 0, len(t) - 1
        while i < j:
            while i < j and not t[i].isalpha():
                i += 1
            while i < j and not t[j].isalpha():
                j -= 1
            t[i], t[j] = t[j], t[i]
            i += 1
            j -= 1
        return ''.join(t)