目录

  • Map接口实现类的特点
  • Map接口的常见方法
  • Map六大遍历方式
  • Map练习1
  • code
  • 编程练习2
  • code
  • 编程练习3
  • 思路
  • code


遇到字符串仅包含小写(或者大写)英文字母的题,都可以试着考虑构造长度为26的数组。这样数组每个位置分别代表一个字母,统计出字母出现的次数。本题中,既要统计字母表中字母出现的次数,也要统计单词中字母出现的次数。如果字母表中字母出现的次数大于等于单词中每种字母出现的次数,那么这个单词就可以由字母表拼写出来。以字母表 "atach"和 词汇"cat"为例,过程图示如下:

java map value 对象吗 java map value为null_java map value 对象吗

code

package cs.kaoyan.javase.com.map;

public class Test7 {
    public static void main(String[] args) {
        String[] words = {"hello","world","leetcode"};
        String chars = "welldonehoneyr";
        int sum1 = countAllWordsLength(words, chars);
        System.out.println(sum1);//10

        String[] words2 = {"cat","bt","hat","tree"};
        String chars2 = "atach";
        int sum2 = countAllWordsLength(words2, chars2);
        System.out.println(sum2);//6

    }

    public static int countAllWordsLength (String[] words,String chars){
        int result = 0;

        int[] charsCount = count(chars);
        //遍历字符串数组
        for (int i = 0; i < words.length; i++) {
            int[] wordsCount = count(words[i]);
            //挨个判断字符串数组中的每一个字符串是否可以由给定的字符组成
            if (contains(wordsCount,charsCount)){
                //累计可以被组成的字符串的长度
                result += words[i].length();
            }
        }

        return result;
    }

    /**
     * 判断给定的字符是否可以组成字符串
     * @param stringCount:一个数组,存储待判断字符串的字母个数
     * @param charCount:一个数组,存储给定字符串的字母个数
     * @return:可以组成返回true,否则返回false
     */
    public static boolean contains(int[] stringCount,int[] charCount){
        for (int i = 0; i < 26; i++) {
            //如果待判断的字符串中某个单词出现的次数大于
            //给定字符串中某个字母出现的次数,表明不能组成这个字符串
            if (stringCount[i] > charCount[i]){
                return false;
            }
        }

        return true;
    }

    /**
     * 计算一个单词中26个字母出现的次数
     * @param s:传入一个单词
     * @return:一个整型数组
     */
    public static int[] count(String s){
        //新建一个整型数组,用来存放每个英文字母出现的次数
        int[] charCountArray = new int[26];
        //遍历字符串
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            charCountArray[(int)c - 'a'] += 1;
        }

        return charCountArray;
    }
}