LeetCode 5637. Determine whether the two halves of a string are similar

Gives you an even-length string s. Split it into two halves of the same length, the first half is a and the second half is b.

The premise that two strings are similar is that they both contain the same number of vowels ('a','e','i','o','u','A','E','I',' O','U'). Note that s may contain both uppercase and lowercase letters.

If a and b are similar, return true; otherwise, return false.

Just count the number of vowels in the front and back parts:

class Solution {
    
    
public:
    bool isVowel(char c) {
    
    
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||
            c == 'A' ||c == 'E' ||c == 'I' ||c == 'O' ||c == 'U') {
    
    
            return true;
        }

        return false;
    }
 
    bool halvesAreAlike(string s) {
    
    
        size_t num = 0;
        for (size_t i = 0; i < s.size(); ++i) {
    
    
            if (i <= s.size() / 2 - 1) {
    
    
                num += isVowel(s[i]);
            } else {
    
    
                num -= isVowel(s[i]);
            }
        }

        return num == 0;
    }
};

Guess you like

Origin blog.csdn.net/tus00000/article/details/111822979