📜

Count Vowels

Count Vowels - Explanation

쉬움 문자열 O(n) O(n)

Problem Summary

Write a function that counts the number of vowels (a, e, i, o, u) in a string.

Go to Problem →

Detailed Explanation

이 문제는 **문자열 검색**과 **배열 필터링**을 결합하여 특정 문자를 세는 방법을 학습합니다. **전략: 모음 목록 정의** 대소문자 모든 모음을 포함하는 문자열 `'aeiouAEIOU'`를 만듭니다. 이렇게 하면 대소문자를 별도로 처리하지 않아도 됩니다. **includes 메서드** `includes()`는 문자열이나 배열에 특정 요소가 있는지 확인합니다: `'aeiouAEIOU'.includes('e')` → true `'aeiouAEIOU'.includes('x')` → false **처리 과정 (예: "hello")** 1. split('') → ['h', 'e', 'l', 'l', 'o'] 2. filter로 모음만 선택 → ['e', 'o'] 3. length로 개수 확인 → 2 **대안적 구현 방법** - 정규표현식: `(str.match(/[aeiou]/gi) || []).length` - for 루프로 직접 카운트 - reduce 사용 **정규표현식 방법의 장점** `/[aeiou]/gi`에서 `i` 플래그가 대소문자 구분 없이 매칭하므로 더 간결합니다.

Solution Code

solution.js
function countVowels(str) {
  const vowels = 'aeiouAEIOU';
  return str.split('').filter(char => vowels.includes(char)).length;
}

Key Concepts from This Problem

1. includes 메서드
2. filter 메서드
3. 문자열 검색
4. 대소문자 처리

Common Mistakes

대문자 모음을 놓치는 경우 - A, E, I, O, U도 모음입니다
split 없이 문자열에 직접 filter를 사용하려고 하는 경우
includes 대신 indexOf를 사용할 때 -1 체크를 잘못하는 경우

Hints

Hint 1: 모음 목록을 문자열이나 배열로 만드세요.
Hint 2: 각 문자가 모음인지 확인하세요.
Hint 3: 대소문자 모두 고려해야 합니다.

Complexity Analysis

Time Complexity

O(n)

Grows linearly with input size

Space Complexity

O(n)

Uses memory proportional to input size

Related Tags

#문자열 #filter #includes