.Zzumbong

[leetCode/JS] 1704. Determine if String Halves Are Alike 본문

coding test/leetCode

[leetCode/JS] 1704. Determine if String Halves Are Alike

쭘봉 2022. 12. 1. 13:43

난이도 [ 😊 ] 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.

 

짝수 길이 string s를 반 나눠서 포함된 모음의 갯수가 똑같으면 true.

 

 

입출력 예

Example 1:

Input: s = "book"
Output: true
Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike.

 

Example 2:

Input: s = "textbook"
Output: false
Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike.
Notice that the vowel o is counted twice.

 

 

Constraints

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

 

 


 

 

내 솔루션

  • 문자열을 2개로 나눈다기보단 중간 index를 기준으로
  • i가 중간 index 보다 작을 땐 -1, 클 땐 +1을 하여서 count를 구한다.
  • 만약 count가 0이되면 모음의 숫자가 똑같기 때문에 true가 된다.
/**
 * @param {string} s
 * @return {boolean}
 */
var halvesAreAlike = function(s) {
  const vowels = ['a', 'e', 'i', 'o', 'u']
  s = s.toLowerCase();
  let count = 0;
  for(let i = 0; i < s.length; i++) {
    if(vowels.includes(s[i])) {
      count = count + (i < s.length/2 ? -1 : +1) 
    }
  }
  return count === 0;
};

 

감상평

  • 나름 빠른편!
Comments