2023年10月10日 星期二

10/9 每日一題(所有非英文字母的順序固定不變, 英文字母全部顛倒, stack)

Given a string s, reverse the string according to the following rules:

  • All the characters that are not English letters remain in the same position.
  • All the English letters (lowercase or uppercase) should be reversed.

Return s after reversing it.

 

Example 1:

Input: s = "ab-cd"
Output: "dc-ba"

Example 2:

Input: s = "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"

Example 3:

Input: s = "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"

 

Constraints:

  • 1 <= s.length <= 100
  • s consists of characters with ASCII values in the range [33, 122].
  • s does not contain '\"' or '\\'.

 class Solution:

    def reverseOnlyLetters(self, s: str) -> str:
        stack=[]
        sym=[]
        for i in s:
            if i.isalpha():
                stack.append(i)
            else:
                sym.append(i)
        print(f'stack={stack}')
        res=[]
        letter=''
        for i,ele in enumerate(s):
            if ele.isalpha():
                letter+=stack.pop()
            else:
                res.append(letter)
                letter=''
        res.append(letter)
        result=''
        n=0
        for i in res:
            result +=i
            if n < len(sym):
                result+=sym[n]
                n+=1
        if n < len(sym):
            result+=sym[n]
            n+=1
        return result
----------------
class Solution:
    def reverseOnlyLetters(self, s: str) -> str:
        l,r= 0 , len(s)-1
        s = list(s)
        while l<r:
            while not s[l].isalpha() and l<r:
                l+=1
            while not s[r].isalpha() and l<r:
                r-=1
            s[l],s[r] = s[r],s[l]
            l+=1
            r-=1
        return "".join(s)
       
       
       

-----------------------

class Solution:
    def reverseOnlyLetters(self, s: str) -> str:
        letters = [i for i in s if i.isalpha()][::-1]
        for ind,ch in enumerate(s):
            if not ch.isalpha():
                letters.insert(ind,ch)
        return "".join(letters)

標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁