넘치게 채우기

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

PS/LeetCode

[LeetCode] 1704. Determine if String Halves Are Alike

riveroverflow 2024. 1. 12. 09:28
728x90
반응형

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

 

Determine if String Halves Are Alike - LeetCode

Can you solve this real interview question? 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 t

leetcode.com

leetcode - Determine if String Halves Are Alike

문제 유형 : 문자열 처리

문제 난이도 : Easy

 

문제

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.

 

당신은 문자열 s를 받는다. 짝수 길이이고, 절반 기준으로 나눴을 때, 앞부분은 a, 뒷부분을 b라고 하자.

두 문자열들은 모음의 개수가 같으면 비슷하다고 할 수 있다. s에는 대소문자 모두 올 수 있음을 명심하라.

a와 b가 비슷하면 true를, 아니면 false를 반환하시오.

 

 

풀이

s의 길이를 n이라고 했을 때, 0~n/2-1까지의 모음의 개수를 a, n/2 ~ n-1까지의 모음의 개수를 b에 저장한다.

모음은 따로 집합 자료구조에 저장해서, 빠르게 찾을 수 있도록 한다.

매번 인덱스마다 문자가 모음 집합에 있는지 알아보고, 모음이면 개수를 1씩 올리면 된다.

 

a와 b가 같으면 true, 다르면 false를 반환시키면 된다.

 

 

코드

C++

class Solution {
public:
    bool halvesAreAlike(string s) {
        const int n = s.size();
        set<char> vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
        int a = 0,b=0;

        for(int i = 0; i < n/2; i++) {
            if(vowels.find(s[i]) != vowels.end()) a++;
        }

        for(int i = n/2; i < n; i++) {
            if(vowels.find(s[i]) != vowels.end()) b++;
        }
        return a == b;
    }
};
 
 
728x90
반응형