[LeetCode刷題筆記] 1704 – 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.

 

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.

Example 3:

Input: s = "MerryChristmas"
Output: false

Example 4:

Input: s = "AbCdEfGh"
Output: true

 

Constraints:

  • 2 <= s.length <= 1000

  • s.length is even.

  • s consists of uppercase and lowercase letters.

一刷題解(雙指針):

       這一題給了我們一個長度為偶數的字母數組(包括大小寫),要求我們檢查這個數組前半與後半之間的元素,是否存在相同數量的元音字母(a/A, e/E, i/I, o/O, u/U)。我們可以先用一個HashSet放著所有元音字母,然後在數組的頭部和尾部各使用一個指針和一個用於計算元音字母數量的計數器。兩個指針同時往數組的中央移動,並在移動的過程中檢查當前字母是否為元音字母,是則使該部分的元音字母計數器+1。當左右兩邊的指針移動到中間後,跳出循環,返回左右兩邊的計數器計數是否相等。

public class Solution {
   public bool HalvesAreAlike(string s) {
       HashSet<char> set = new HashSet<char>()
      {
           'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'
      };

       int mid = s.Length / 2;

       int left = 0;
       int leftVowelCnt = 0;

       int right = s.Length - 1;
       int rightVowelCnt = 0;

       while(left < mid && right >= mid)
      {
           if (set.Contains(s[left])) { leftVowelCnt++; }
           if (set.Contains(s[right])) { rightVowelCnt++; }
           left++;
           right--;                
      }
       
       return leftVowelCnt == rightVowelCnt;        
  }
}