소프트웨어에 대한 모든 것

LeetCode 풀기 - 1859. Sorting the Sentence 본문

카테고리 없음

LeetCode 풀기 - 1859. Sorting the Sentence

앤테바 2021. 11. 4. 08:35
반응형

1859. Sorting the Sentence

https://leetcode.com/problems/sorting-the-sentence/

 

Sorting the Sentence - 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

문제)

솔루션1)

1. sentence을 space로 split
2. 단어의 수를 세고, 단어 수 사이즈 만큼 array 생성
3. 각 단어를 반복문을 돌면서 단어의 마지막을 indexing해서 word position 획득
4. array[word position]에 단어를 indexing을 제거한 다음 추가   

class Solution:
    def sortSentence(self, s: str) -> str:
        words = s.split()
        len_word = len(words)
        
        arr = [0] * len_word
        
        for word in words:
            word_position = int(word[-1]) - 1
            word_without_position = word[0:-1]
            arr[word_position] = word_without_position
        return ' '.join(arr)

솔루션2)

class Solution:
    def sortSentence(self, s: str) -> str:
        words = [word[-1] + word[:-1] for word in s.split()]
        words.sort()
        
        ret = ''
        for word in words:
            ret += word[1:] + ' '
            
        return ret[:-1]

 

반응형
Comments