관리 메뉴

솜씨좋은장씨

[leetCode] 1451. Rearrange Words in a Sentence (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 1451. Rearrange Words in a Sentence (Python)

솜씨좋은장씨 2021. 1. 20. 00:15
728x90
반응형

Given a sentence text (A sentence is a string of space-separated words) in the following format:

  • First letter is in upper case.
  • Each word in text are separated by a single space.

Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order.

Return the new text following the format shown above.

 

Example 1:

Input: text = "Leetcode is cool"
Output: "Is cool leetcode"
Explanation: There are 3 words, "Leetcode" of length 8, "is" of length 2 and "cool" of length 4.
Output is ordered by length and the new first word starts with capital letter.

Example 2:

Input: text = "Keep calm and code on"
Output: "On and keep calm code"
Explanation: Output is ordered as follows:
"On" 2 letters.
"and" 3 letters.
"keep" 4 letters in case of tie order by position in original text.
"calm" 4 letters.
"code" 4 letters.

Example 3:

Input: text = "To be or not to be"
Output: "To be or to be not"

 

Constraints:

  • text begins with a capital letter and then contains lowercase letters and single space between words.
  • 1 <= text.length <= 10^5

Solution

class Solution:
    def arrangeWords(self, text: str) -> str:
        word_list = text.split(" ")
        
        info_list = []
        
        for i, word in enumerate(word_list):
            info_list.append([i, len(word), word])
            
        sorted_list = sorted(info_list, key=lambda x: (x[1], x[0]))
        
        word_list = [word[2].lower() for word in sorted_list]
        
        character_list = list(word_list[0])
        
        character_list[0] = character_list[0].upper()
        
        word_list[0] = "".join(character_list)
        
        return " ".join(word_list)

Solution 풀이

먼저 split을 통하여 text를 단어단위로 나누어줍니다.

그 다음 [ index, 단어의 길이, 단어 ] 와 같은 형태의 리스트를 만들어줍니다.

만든 다음 단어의 길이, index 순서 기준으로 sorting 합니다.

sorting 한 리스트에서 단어만 뽑아오는데 이때 각 단어에서의 대문자를 모두 소문자로 바꾸어 줍니다.

그 다음 맨 처음에 존재하는 단어의 맨 앞글자를 대문자로 바꾸어줍니다.

마지막으로 다시 하나의 text로 join을 해주면 됩니다.

 

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments