작심삼일

[LeetCode] 1704 | Determine if String Halves Are Alike | Python 본문

스터디/코테

[LeetCode] 1704 | Determine if String Halves Are Alike | Python

yun_s 2022. 12. 1. 09:47
728x90
반응형

문제 링크: https://leetcode.com/problems/determine-if-string-halves-are-alike/


문제

You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half.

Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters.

Return true if a and b are alike. Otherwise, return false.


조건

  • 2 <= s.length <= 1000
  • s.length is even.
  • s consists of uppercase and lowercase letters.

내 풀이

모음인지 여부를 알려주기 위한 함수 is_vowel을 만든다.

주어진 문장(s)를 앞(front)과 뒤(end)로 자른다.

is_vowel을 이용해서 front의 해당 위치의 원소들이 모음이면 1, 자음이면 0을 가지는 또다른 array를 만든 후, 그 array의 sum을 front_vowels에 저장한다. (이 뜻은 front 안에 있는 모음의 수를 세는 것이다.)

같은 방법으로 end_vowels에 end 안에 있는 모음의 수를 저장한다.

 

만약 front_vowels가 end_vowels와 같다면 True를 리턴하고, 그렇지 않다면 False를 리턴하면 된다.


코드

class Solution:
    def halvesAreAlike(self, s: str) -> bool:
        def is_vowel(ch):
            return True if ch in ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] else False
        
        N = len(s)
        half = N//2
        front, end = s[:half], s[half:]
        
        front_vowels = sum([1 if is_vowel(x) else 0 for x in front])
        end_vowels = sum([1 if is_vowel(x) else 0 for x in end])
        
        return True if front_vowels == end_vowels else False
728x90
반응형
Comments