华为OD-D卷万能字符单词拼写
有一个字符串数组words和一个字符串chars。
假如可以用chars中的字母拼写出words中的某个“单词”(字符串),那么我们就认为你掌握了这个单词。
words的字符仅由 a-z 英文小写字母组成。 例如: abc
chars 由 a-z 英文小写字母和 “?”组成。其中英文问号“?”表示万能字符,能够在拼写时当做任意一个英文字母。 例如: "?" 可以当做 "a"等字母。
注意:每次拼写时,chars中的每个字母和万能字符都只能使用一次。
输出词汇表words中你掌握的所有单词的个数。 没有掌握任何单词,则输出0。
输入描述:
第1行输入数组words的个数,记为N。
从第2行开始到第N+1行依次输入数组words的每个字符串元素。
第N+2行输入字符串chars。输出描述:
输出一个整数,表示词汇表words中你掌握的单词个数。
备注:
注意:
1 <= words.length <= 100
1 <= words[i].length, chars.length <= 100
所有字符串中都仅包含小写英文字母、英文问号
题目解析:本质还是判断一个字符串是否能由另一个字符串组成,字符串由26个字母组成,建一个大小为26的数组来计算每个字母出现的次数即可!
注意:要判断的一个数组中的单词是否学过,加一个循环就行,而且还需要对通配符进行单独的统计。
import java.util.Scanner;public class Main {public static void main(String[] args) {
// String[] words = new String[]{"cat", "bt", "hat", "tree"};
// String chars = "atach??";// 处理数据Scanner scanner = new Scanner(System.in);int n = scanner.nextInt();String[] words = new String[n];for (int i = 0; i < n; i++) {words[i] = scanner.next();}String chars = scanner.next();// 计算chars里面出现的字符数和?的次数int[] countChars = new int[26];int count = 0;for (int i = 0; i < chars.length(); i++) {if (chars.charAt(i) == '?') {count++;continue;}countChars[chars.charAt(i) - 'a']++;}int result = 0;// 遍历每个单词,查看是否掌握for (int i = 0; i < words.length; i++) {if (isMasterWord(words[i], countChars, count)) {result++;}}System.out.println(result);}public static boolean isMasterWord(String word, int[] countChars, int count) {for (int i = 0; i < word.length(); i++) {countChars[word.charAt(i) - 'a']--;if (countChars[word.charAt(i) - 'a'] < 0) {count--;// ? 不够用了直接返回falseif (count < 0) {return false;}}}return true;}
}