.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;
};

 

๊ฐ์ƒํ‰

  • ๋‚˜๋ฆ„ ๋น ๋ฅธํŽธ!
0 Comments
๋Œ“๊ธ€์“ฐ๊ธฐ ํผ