무냐의 개발일지

2114. Maximum Number of Words Found in Sentences 본문

LeetCode 코딩테스트

2114. Maximum Number of Words Found in Sentences

무냐코드 2024. 4. 13. 23:43

👩‍💻 문제

 

A sentence is a list of words that are separated by a single space with no leading or trailing spaces.
You are given an array of strings sentences, where each sentences[i] represents a single sentence.
Return the maximum number of words that appear in a single sentence.

Example 1:
Input: sentences = ["alice and bob love leetcode", "i think so too", "this is great thanks very much"]
Output: 6
Explanation: 
- The first sentence, "alice and bob love leetcode", has 5 words in total.
- The second sentence, "i think so too", has 4 words in total.
- The third sentence, "this is great thanks very much", has 6 words in total.
Thus, the maximum number of words in a single sentence comes from the third sentence, which has 6 words.

 

 

💡 풀이 #1 (첫번째 직관적 답안)

class Solution:
    def mostWordsFound(self, sentences: List[str]) -> int:
        res = []
        for sentence in sentences:
            a = len(sentence.split())
            res.append(a)
        return max(res)

 

 

💡 풀이 #2 (다른 방법들)

class Solution:
    def mostWordsFound(self, sentences: List[str]) -> int:
        answer = 0
        for sentence in sentences:
            answer = max(answer, len(sentence.split()))
        return answer

 

list에 append하는 과정 없이, 바로 answer= 0 과 len(sentence.split()) 을 비교하여 max 값을 출력할 수 있다 

 

class Solution:
    def mostWordsFound(self, sentences: List[str]) -> int:
        max_space = 0
        for i in sentences:
            max_space = max(max_space, i.count(' ')+1)
        return max_space

 

이것도 비슷한 맥락인데, 단어 자체를 세지 않고, 그 사이에 있는 공백을 count하고서 거기 +1 하면 단어수가 되는 원리를 이용한 방법이다.

 

✍️ 해설

문장들을 sentence으로 분리해주고, 각각 공백 기준으로 split해주면

['w', 'jrpihe', 'zsyqn', 'l', 'dxchifbxlasaehj'] ['nmmfrwyl', 'jscqyxk', 'a', 'xfibiooix', 'xolyqfdspkliyejsnksfewbjom'] ['xnleojowaxwpyogyrayfgyuzhgtdzrsyococuqexggigtberizdzlyrdsfvryiynhg'] ['krpwiazoulcixkkeyogizvicdkbrsiiuhizhkxdpssynfzuigvcbovm'] ['rgmz', 'rgztiup', 'wqnvbucfqcyjivvoeedyxvjsmtqwpqpxmzdupfyfeewxegrlbjtsjkusyektigr'] ['o', 'lgsbechr', 'lqcgfiat', 'pkqdutzrq', 'iveyv', 'iqzgvyddyoqqmqerbmkxlbtmdtkinlk'] ['hrvh', 'efqvjilibdqxjlpmanmogiossjyxepotezo'] ['qstd', 'zui', 'nbbohtuk'] ['qsdrerdzjvhxjqchvuewevyzlkyydpeeblpc']

이런 식으로 각각의 리스트가 완성된다. 각 리스트의 길이를 구하면 int형태로

5 5 1 1 3 6 2 3 1

이런식으로 출력되고,

이를 result = [] 에 담은 후 max 값을 구한다 

 

🥳 배운점

count함수

max_space를 0으로 넣고, 바로 max(max_space, 진짜 내가 비교할 값) 이런 식으로 코드를 간결하게 만들 수 있다