LeetCode 917. Reverse letters only (python)

Keywords: ascii

Title Link

Title Description:

Given a string S, the "reversed" string is returned, in which characters that are not letters are left in place, and the positions of all letters are reversed.

Example 1:

Input: "ab CD"
Output: "DC Ba"
Example 2:

Enter: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"
Example 3:

Type: "test1ng leet = code-q!"
Output: "qedo1ct eelg = nte-t!"

Tips:

S.length <= 100
33 <= S[i].ASCIIcode <= 122
S does not contain \ or“

Solutions:

Traverse the string from both ends to the middle. If both the front and the back are letters, exchange them (since the string cannot be modified, convert the string to a list first). If not, compare the next one.
P.s.33 < = s [i]. ASCII code < = 122 can be directly used to judge whether it is a letter or not

class Solution:
    def reverseOnlyLetters(self, S: str) -> str:
        begin=0
        end=len(S)-1
        S=list(S)
        while begin<end:
            if ((S[begin]>='a' and S[begin]<='z') or (S[begin]>='A' and S[begin]<='Z')) and ((S[end]>='a' and S[end]<='z') or (S[end]>='A' and S[end]<='Z')):#Both the front and back are letters
                S[begin],S[end]=S[end],S[begin]
                begin+=1
                end-=1
            elif (S[begin]>='a' and S[begin]<='z') or (S[begin]>='A' and S[begin]<='Z'):#Not followed by letters
                end-=1
            elif ((S[end]>='a' and S[end]<='z') or (S[end]>='A' and S[end]<='Z')):#It's not preceded by letters
                begin+=1
            else:
                begin+=1
                end-=1
        return ''.join(S)
                

Other people's succinct writing of p.s
The. isalpha() method detects whether a string is made up of only letters

class Solution:
    def reverseOnlyLetters(self, S: 'str') -> 'str':
        S = list(S)
        i, j = 0, len(S) - 1
        while i < j:
            if S[i].isalpha() and S[j].isalpha():
                S[i], S[j] = S[j], S[i]
                i += 1
                j -= 1
            if not S[i].isalpha():
                i += 1
            if not S[j].isalpha():
                j -= 1
            
        return "".join(S)

Posted by kfir91 on Wed, 13 Nov 2019 08:08:19 -0800