컴퓨터공학/LeetCode 1000

[LeetCode] 557. Reverse Words in a String III

saurus2 2022. 9. 23. 01:52

557. Reverse Words in a String III

Easy

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.

문제 풀이

  1. 문자열이 주어진다. 띄어쓰기로 나누어져 있다. 띄어쓰기마다 존재하는 단어들을 뒤집어야한다.
  2. 스트링의 제한을 보면 5 * 10^4 이기 때문에, N^2 으로 풀어도 문제없을 것 같다. (브루트 포스)
  3. 파이썬의 스플릿과 슬라이스를 사용하거나 투포인터를 사용해서 풀 수 있다. 

소스 코드

투포인터

class Solution:
    def reverseWords(self, s: str) -> str:
        s_size = len(s)
        space_idx = -1
        s = list(s)
        for i in range(s_size + 1):
            if i == s_size or s[i] == ' ':
                start_idx = space_idx + 1
                end_idx = i - 1
                while start_idx < end_idx:
                    s[start_idx], s[end_idx] = s[end_idx], s[start_idx]
                    start_idx += 1
                    end_idx -= 1
                space_idx = i
        s = ''.join(s)
        return s

스플릿 & 슬라이스

class Solution:
    def reverseWords(self, s: str) -> str:
        result = split(' ', s)
        result = ' '.join([word[::-1] for word in result])
        return result