赞
踩
有一个字符串数组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
所有字符串中都仅包含小写英文字母、英文问号
- 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--;
- // ? 不够用了直接返回false
- if (count < 0) {
- return false;
- }
- }
- }
- return true;
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。