반응형
https://leetcode.com/problems/reverse-words-in-a-string/
Reverse Words in a String - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
단어들을 뒤집는 문제로 스페이스 처리가 약간 귀찮은 문제이다.
일단 기능적으로 돌아가기만 하도록 빨리 짜봄
class Solution:
def reverseWords(self, s: str) -> str:
words = []
word = ''
for c in s:
if c == ' ':
if len(word) != 0:
words.append(word)
word = ''
else:
word += c
if len(word) != 0:
words.append(word)
return ' '.join(reversed(words))
time complexity: O(n)
space complexity: O(n)
아주 무난한 코드가 나옴......
면접이었으면 탈락각인가 생각했는데
괜찮은 코드였네....??(나 보기보다 코딩을 잘할지도..?!)
요즘 regular expression 쓰는걸 좋아해서 그걸 써보면 좋겠다 생각해서 새로만든 코드
import re
class Solution:
def reverseWords(self, s: str) -> str:
return ' '.join(reversed(re.sub(' +',' ',s).split(' '))).strip()
한줄짜리 코드로 바꿈(파이썬 최고)
반응형
'Computer Science > CODINGTEST_PRACTICE' 카테고리의 다른 글
[LeetCode] 26. Remove Duplicates from Sorted Array 기록 (0) | 2022.11.21 |
---|---|
[LeetCode] 21. Merge Two Sorted Lists 기록 (0) | 2022.11.16 |
[LeetCode] 20. Valid Parentheses 기록 (2) | 2022.11.12 |
[LeetCode] 14. Longest Common Prefix (python3) (0) | 2022.07.12 |
[LeetCode] 13. Roman to Integer (python3) (0) | 2022.07.08 |