• 1704. Determine if String Halves Are Alike (E)


    Determine if String Halves Are Alike (E)

    题目

    You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half.

    Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters.

    Return true if a and b are alike. Otherwise, return false.

    Example 1:

    Input: s = "book"
    Output: true
    Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike.
    

    Example 2:

    Input: s = "textbook"
    Output: false
    Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike.
    Notice that the vowel o is counted twice.
    

    Example 3:

    Input: s = "MerryChristmas"
    Output: false
    

    Example 4:

    Input: s = "AbCdEfGh"
    Output: true
    

    Constraints:

    • 2 <= s.length <= 1000
    • s.length is even.
    • s consists of uppercase and lowercase letters.

    题意

    判断一个偶数长度的字符串的前半部分和后半部分是否包含相同数量的元音字符。

    思路

    直接模拟统计即可。


    代码实现

    Java

    class Solution {
        public boolean halvesAreAlike(String s) {
            int count = 0;
            Set<Character> vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));
            
            for (int i = 0; i < s.length() / 2; i++) {
                if (vowels.contains(s.charAt(i))) count++;
            }
            for (int i = s.length() / 2; i < s.length(); i++) {
                if (vowels.contains(s.charAt(i))) count--;
            }
            
            return count == 0;
        }
    }
    
  • 相关阅读:
    Golang之排序算法
    Golang之一个简单的聊天机器人
    golang之流程控制(注意点)
    golang之指针
    vs code中自动添加注释插件koroFileHeader
    stack栈、heap堆的说明图
    c语言中的数据类型的最大最小值
    数组问题:a与&a有的区别
    STM32F10x之NVIC
    大小端的另一种测试方法
  • 原文地址:https://www.cnblogs.com/mapoos/p/14628013.html
Copyright © 2020-2023  润新知