LeetCode-2586. 统计范围内的元音字符串数

Problem: 2586. 统计范围内的元音字符串数
每日一题。

文章目录

  • 思路
  • Code
    • ArrayList集合
    • 数组

思路

利用一个数组来存储元音字母,通过遍历范围内的字符串找出符合条件的。

Code

ArrayList集合


class Solution {
    public int vowelStrings(String[] words, int left, int right) {
        List<Character> list = new ArrayList<>();
        list.add('a');
        list.add('e');
        list.add('i');
        list.add('o');
        list.add('u');
        int res = 0;
        int len = words.length;
        for (int l = left; l <= right; l++) {
            String s1 = words[l];
            int slen = s1.length();
            char first = s1.charAt(0);
            char end = s1.charAt(slen - 1);
            if (list.contains(first) && list.contains(end)) {
                res++;
            }
        }
        return res;
    }
}

数组

class Solution {
    public int vowelStrings(String[] words, int left, int right) {
        int[] arr = new int[26];
        arr['a' - 'a']++;
        arr['e' - 'a']++;
        arr['i' - 'a']++;
        arr['o' - 'a']++;
        arr['u' - 'a']++;
        int res = 0;
        for (int l = left; l <= right; l++) {
            int length = words[l].length();
            if (arr[words[l].charAt(0) - 'a'] > 0 && arr[words[l].charAt(length - 1) - 'a'] > 0) {
                res++;
            }
        }
        return res;
    }
}

你可能感兴趣的:(算法学习与刷题,leetcode,算法,职场和发展)