public boolean halvesAreAlike(String s) {
char[] a = s.toCharArray();
int size = a.length / 2;
HashSet<Character> vowels = new HashSet<Character>(Arrays.asList('a','e','i','o','u','A', 'E', 'I', 'O', 'U'));
int countA = 0, countB = 0;
// Counting vowels in the first half
for (int i = 0; i < size; i++) {
if (vowels.contains(a[i])) {
countA++;
}
}
// Counting vowels in the second half
for (int i = size; i < a.length; i++) {
if (vowels.contains(a[i])) {
countB++;
}
}
return countA == countB;
}
Problem: https://leetcode.com/problems/determine-if-string-halves-are-alike/description/
Breaking Down the Solution
- Converting String to Char Array:
- The input string
s
is converted into a character arraya
. This facilitates easy traversal and access to individual characters.
- The input string
- Initialization and Set of Vowels:
- A HashSet
vowels
is created to store the vowels that need to be checked. - The size of the array is calculated, representing the midpoint of the string.
- A HashSet
- Vowel Counting in First Half:
- A loop traverses the first half of the character array, incrementing
countA
for each vowel encountered.
- A loop traverses the first half of the character array, incrementing
- Vowel Counting in Second Half:
- Another loop traverses the second half of the character array, incrementing
countB
for each vowel encountered.
- Another loop traverses the second half of the character array, incrementing
- Comparison and Result:
- The method returns
true
ifcountA
equalscountB
, indicating an equal number of vowels in both halves; otherwise, it returnsfalse
.
- The method returns
Conclusion
The Solution
class provides a concise and efficient Java solution to the problem of checking whether two halves of a string contain an equal number of vowels. The use of a HashSet for vowel checking and separate counts for each half ensures simplicity and readability. As we navigate through the intricacies of string manipulation, this solution stands as a testament to effective problem-solving in the world of Java programming.