zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    
  • 相关阅读:
    printf里的=、++
    线程也疯狂-----异步编程
    自己搭建node服务器环境(请求静态资源、get请求、post请求)
    React学习
    2020.10-2021-01总结
    接圈的作用和缺点
    CWnd,HWND; CDC,HDC
    Python通过requests模块处理form-data请求格式
    element-ui resetFields 无效的问题
    用python 将数字每三组分割
  • 原文地址:https://www.cnblogs.com/mapoos/p/14628013.html
Copyright © 2011-2022 走看看