1704. Determine if String Halves Are Alike

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

  1. Converting String to Char Array:
    • The input string s is converted into a character array a. This facilitates easy traversal and access to individual characters.
  2. 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.
  3. Vowel Counting in First Half:
    • A loop traverses the first half of the character array, incrementing countA for each vowel encountered.
  4. Vowel Counting in Second Half:
    • Another loop traverses the second half of the character array, incrementing countB for each vowel encountered.
  5. Comparison and Result:
    • The method returns true if countA equals countB, indicating an equal number of vowels in both halves; otherwise, it returns false.

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.

Related Post