1704. 判断字符串的两半是否相似

题目:给你一个偶数长度的字符串 s 。将其拆分成长度相同的两半,前一半为 a ,后一半为 b 。

两个字符串 相似 的前提是它们都含有相同数目的元音('a','e','i','o','u','A','E','I','O','U')。注意,s 可能同时含有大写和小写字母。

如果 a 和 b 相似,返回 true ;否则,返回 false 。

示例 1:

输入:s = "book"
输出:true
解释:a = "bo" 且 b = "ok" 。a 中有 1 个元音,b 也有 1 个元音。所以,a 和 b 相似。
示例 2:

输入:s = "textbook"
输出:false
解释:a = "text" 且 b = "book" 。a 中有 1 个元音,b 中有 2 个元音。因此,a 和 b 不相似。
注意,元音 o 在 b 中出现两次,记为 2 个。

1.原创

class Solution {
public:
    int num_Yuan(string ss){
        int count = 0;
        const string p="aeiouAEIOU";
        for (auto i : ss) {
            if (p.find(i) != string::npos)
                count+=1;             
        }
        return count;
    }
    bool halvesAreAlike(string s) {
        int n = s.length();
        int count_a,count_b;
        string a = s.substr(0,n/2);
        string b = s.substr(n/2,n);
        count_a = num_Yuan(a);
        count_b = num_Yuan(b);
        if (count_a == count_b)
            return true;
        else
            return false;

    }
};

2.题解答案

class Solution {
public:
    bool halvesAreAlike(string s) {
        int n = s.size();
        int total_a = 0, total_b = 0;
        for (int i = 0; i < n; i++) {
            char c = s[i];         
            if ((c == 'a') or (c == 'e') or (c == 'i') or (c == 'o') or(c == 'u') or (c == 'A') or (c == 'E') or (c == 'I') or (c == 'O') or (c == 'U')) {
                if (i < n / 2)
                    total_a++;
                else
                    total_b++;
            }
        }
        return total_a == total_b;
    }
};

作者:liang-lin-123
链接:https://leetcode-cn.com/problems/determine-if-string-halves-are-alike/solution/fei-chang-
原文地址:https://www.cnblogs.com/USTC-ZCC/p/14446223.html