leetcode 1704. Determine whether the two halves of a string are similar (2022.11.11)

【题目】1704. Determine whether the two halves of a string are similar

You are given a string s of even length. Split it into two halves of equal length, the first half being a and the second half being b.

Two strings are similar if 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.

Returns true if a and b are similar; otherwise, returns false.

Example 1:

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

Example 2:

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

hint:

2 <= s.length <= 1000
s.length 是偶数
s 由 大写和小写 字母组成

[Problem-solving ideas 1]

class Solution {
    
    
    public boolean halvesAreAlike(String s) {
    
    
        String a = s.substring(0, s.length() / 2);
        String b = s.substring(s.length() / 2);
        String h = "aeiouAEIOU";
        int sum1 = 0, sum2 = 0;
        for (int i = 0; i < a.length(); i++) {
    
    
            if (h.indexOf(a.charAt(i)) >= 0) {
    
    
                sum1++;
            }
        }
        for (int i = 0; i < b.length(); i++) {
    
    
            if (h.indexOf(b.charAt(i)) >= 0) {
    
    
                sum2++;
            }
        }
        return sum1 == sum2;
    }
}

Guess you like

Origin blog.csdn.net/XunCiy/article/details/128124923