반응형
Notice
Recent Posts
Recent Comments
- Today
- Total
작심삼일
[LeetCode] 557 | Reverse Words in a String III | Python 본문
728x90
반응형
문제 링크: https://leetcode.com/problems/reverse-words-in-a-string-iii/
문제
Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
조건
- 1 <= s.length <= 5 * $10^4$
- 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.
내 풀이
주어진 string을 띄어쓰기(" ")를 기준으로 단어들로 분해한다.
각 단어를 거꾸로 뒤집어서(word[::-1]) 띄어쓰기와 함께 이어붙인다.
위 과정을 반복하고나면 ans의 맨 뒤에 " "가 한 칸 붙게되는데, 이를 제거하고 리턴한다.
코드
class Solution:
def reverseWords(self, s: str) -> str:
ans = ""
for word in s.split(" "):
ans += word[::-1] + ' '
return ans[:-1]
728x90
반응형
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 990 | Satisfiability of Equality Equations | Python (0) | 2022.09.26 |
---|---|
[LeetCode] 1680 | Concatenation of Consecutive Binary Numbers | Python (0) | 2022.09.23 |
[LeetCode] 985 | Sum of Even Numbers After Queries | Python (0) | 2022.09.21 |
[LeetCode] 718 | Maximum Length of Repeated Subarray | Python (0) | 2022.09.20 |
[LeetCode] 609 | Find Duplicate File in System | Python (0) | 2022.09.19 |
Comments