2023年7月29日 星期六

7/30 每日一題(每個子句順序不變, 子句內容反轉)

 Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

 

Example 1:

Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Example 2:

Input: s = "God Ding"
Output: "doG gniD"

 

Constraints:

  • 1 <= s.length <= 5 * 104
  • s contains printable ASCII characters.
  • s does not contain any leading or trailing spaces.
  • There is at least one word in s.
  • All the words in s are separated by a single space.

class Solution:
    def reverseWords(self, s: str) -> str:
        n=len(s)
       
        if n==1:
            return s #只有自身直接返回
        res=s.split()#預設值以空格當作分割
        ans=[] #初始化ans
        for i in range(len(res)):
            ans.append(res[i][-1::-1]) #取每一個子句的反轉+到ans

        return ' '.join(ans) #以空格為間隔加入ans

       
       

------------------參考解答
def reverseWords(s: str) -> str:
    words = s.split()  # Split the string into words by spaces
    reversed_words = [word[::-1] for word in words]  # Reverse each word
    return ' '.join(reversed_words)  # Join the reversed words with spaces and return the result









標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁