leetcode每日一题—1160. 拼写单词

题目描述:在这里插入图片描述
思想:刚看题的时候想用暴力破解来算,可是运行内存和运行时间都会比较长。
这个题由于提示里说明“所有字符都只包含小写英文字母”,借用leetcode中的一句话:凡是和“变位词”、“字母顺序打乱”相关的题目,都考虑统计字母出现的次数。
首先挨个统计字符串数组中每个字符串字母出现的次数;然后统计字母表里每个字母出现的次数。

  • 如果字符串数组里的字符串统计的次数大于字母表里的次数,则不计算;
  • 小于则计算。
class Solution {
    
    
    public int countCharacters(String[] words, String chars) {
    
    
    	int[] chars_count=counts(chars);	//统计字母表中的字母出现的次数
    	int num=0;
    	for (String word : words) {
    
    
			int[] word_count=counts(word);
			if(contains(chars_count, word_count)){
    
    
				num+=word.length();
			}
		}
		return num;
    }
    //检查字母表中的出现次数是否覆盖单词中出现的次数
    boolean contains(int[] chars_count,int[] words_count){
    
    
    	for(int i=0;i<26;i++){
    
    
    		if(chars_count[i]<words_count[i]){
    
    
    			return false;
    		}
    	}
		return true;	
    }
    //统计在26个字母中出现的次数
    public int[] counts(String word){
    
    
    	int[] counters=new int[26];
    	for(int i=0;i<word.length();i++){
    
    
    		char c=word.charAt(i);
    		counters[c-'a']++;
    	}
		return counters;
    	
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42856363/article/details/104924984