mercredi 6 janvier 2021

conditional changes behavior when converted to ternary operator?

I am writing a function that compares the number of vowels in the first half of a string and compares it with the second half, and returns a boolean based on if the number is equal.

Example:

Input: "book"
Output: true

because bo | ok, numVowels = 1, one 'o' in both halves.

My code that works is here

class Solution {
    public boolean halvesAreAlike(String s) {
        Set<Character> set = new HashSet<>(Arrays.asList('a','e','i','o','u','A','E','I','O','U'));                                
        int vowelCount = 0, length = (s.length()%2 == 0) ? s.length()/2 : s.length()/2+1;
        
        boolean pastHalf = false; 
        for (int i = 0; i < s.length(); i++) {
            if (i == length) pastHalf = true; 
            if (pastHalf && set.contains(s.charAt(i))) vowelCount--; 
            else if (!pastHalf && set.contains(s.charAt(i))) vowelCount++; 
        }
        return vowelCount == 0;                                                                    
    }
}

In the if (i == length) pastHalf = true; line, I am checking to see if I have hit the middle of the String. This is a simple boolean. I changed it to this ternary pastHalf = (i == length) ? true : false; and the output was wrong for the test case Ieai. Does anyone know why? I believe that the statements are equivalent.

Aucun commentaire:

Enregistrer un commentaire