Easy
,String
,Counting
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.
Constraints:
2 <= s.length <= 1000
s.length
is even.s
consists of uppercase and lowercase letters.
function halvesAreAlike2(s) {
const vowels = 'aeiouAEIOU';
let count = 0;
for (let i = 0; i < s.length / 2; i++) {
if (vowels.includes(s[i])) count++;
if (vowels.includes(s[s.length - 1 - i])) count--;
}
return count === 0;
}
這題用set會比較慢欸
Marsgoat Dec 1, 2022
class Solution:
def halvesAreAlike(self, s: str) -> bool:
cnt, mid = 0, len(s) // 2
for idx in range(mid):
if s[idx] in 'aeiouAEIOU': cnt += 1
if s[mid+idx] in 'aeiouAEIOU': cnt -= 1
return cnt == 0
Kobe Dec 1, 2022
class Solution {
public boolean halvesAreAlike(String s) {
int cnt = 0;
var vowels = Set.of('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U');
for(int i = 0, j = s.length() - 1; i < j; i++, j--) {
cnt += vowels.contains(s.charAt(i)) ? 1 : 0;
cnt -= vowels.contains(s.charAt(j)) ? 1 : 0;
}
return cnt == 0;
}
}
Java 語法越來越先進
Kobe Dec 1, 2022
function halvesAreAlike(s: string): boolean {
const vowels = 'aeiouAEIOU';
const firstHalf = s.substring(0, s.length / 2);
const lastHalf = s.substring(s.length / 2);
let firstHalfVowelsCount: number = 0;
let lastHalfVowelsCount: number = 0;
firstHalf.split('').forEach((d) => {
if (vowels.includes(d)) firstHalfVowelsCount++;
});
lastHalf.split('').forEach((d) => {
if (vowels.includes(d)) lastHalfVowelsCount++;
});
return firstHalfVowelsCount === lastHalfVowelsCount;
}
function halvesAreAlike(s: string): boolean {
const vowels = 'aeiouAEIOU';
const firstHalf = s.substring(0, s.length / 2);
const lastHalf = s.substring(s.length / 2);
let count: number = 0;
for (let i = 0; i < s.length / 2; i++) {
if (vowels.includes(firstHalf[i])) count++;
if (vowels.includes(lastHalf[i])) count--;
}
return count === 0;
}
sheep Dec 1, 2022