557. Reverse Words in a String III

개꡴·2024λ…„ 6μ›” 14일

leetcode

λͺ©λ‘ 보기
29/51
  • python3

πŸ“Ž Problem

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 = "Mr Ding"
Output: "rM 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.

Pseudocode

  1. Set two strings: one for the result and one for the temporary string.
  2. If character of string is not blank, add character to temp string. If it is, temp will add to the result and be empty.
  3. Return the result.

Code

First code

class Solution:
    def reverseWords(self, s: str) -> str:

        result = ""
        temp = ""
        for i in range(0, len(s)):
            if s[i] == ' ':
                result = result + temp + " "
                temp = ""
            else:
                temp = s[i] + temp
            
        result += temp

        return result

Second code

class Solution:
    def reverseWords(self, s: str) -> str:

        sList = s.split()
        
        for i in range(0, len(sList)):
            sList[i] = sList[i][::-1]

        return ' '.join(sList)

Result

First code

  • Time Complexity: O(n)
  • Space Complexity: O(n)

Second code

  • Time Complexity: O(n)
  • Space Complexity: O(n)
profile
μ•Œμ­λ‹¬μ­ν˜€μš”

0개의 λŒ“κΈ€