소프트웨어에 대한 모든 것

LeetCode 풀기 - 1704. Determine if String Halves Are Alike 본문

알고리즘/LeetCode

LeetCode 풀기 - 1704. Determine if String Halves Are Alike

앤테바 2021. 11. 10. 20:17
반응형

1704. Determine if String Halves Are Alike

https://leetcode.com/problems/determine-if-string-halves-are-alike/

 

Determine if String Halves Are Alike - 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)

class Solution:
    def halvesAreAlike(self, s: str) -> bool:
        vowels =  ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')
        a = s[:len(s)//2]
        b = s[len(s)//2:]
        
        a_vowel_count = 0
        b_vowel_count = 0
        for a_c, b_c in zip(a, b):
            if a_c in vowels:
                a_vowel_count += 1
            if b_c in vowels:
                b_vowel_count += 1

        return a_vowel_count == b_vowel_count

솔루션2)

Counter() 객체를 사용한 short code

class Solution:
    def halvesAreAlike(self, s: str) -> bool:
        vowels =  ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')
        a, b = Counter(s[:len(s)//2]), Counter(s[len(s)//2:])         
        return sum([a[v] for v in vowels]) == sum([b[v] for v in vowels])

 

반응형
Comments