当前位置:   article > 正文

华为OD-D卷万能字符单词拼写

华为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的数组来计算每个字母出现的次数即可!

注意:要判断的一个数组中的单词是否学过,加一个循环就行,而且还需要对通配符进行单独的统计。

  1. import java.util.Scanner;
  2. public class Main {
  3. public static void main(String[] args) {
  4. // String[] words = new String[]{"cat", "bt", "hat", "tree"};
  5. // String chars = "atach??";
  6. // 处理数据
  7. Scanner scanner = new Scanner(System.in);
  8. int n = scanner.nextInt();
  9. String[] words = new String[n];
  10. for (int i = 0; i < n; i++) {
  11. words[i] = scanner.next();
  12. }
  13. String chars = scanner.next();
  14. // 计算chars里面出现的字符数和?的次数
  15. int[] countChars = new int[26];
  16. int count = 0;
  17. for (int i = 0; i < chars.length(); i++) {
  18. if (chars.charAt(i) == '?') {
  19. count++;
  20. continue;
  21. }
  22. countChars[chars.charAt(i) - 'a']++;
  23. }
  24. int result = 0;
  25. // 遍历每个单词,查看是否掌握
  26. for (int i = 0; i < words.length; i++) {
  27. if (isMasterWord(words[i], countChars, count)) {
  28. result++;
  29. }
  30. }
  31. System.out.println(result);
  32. }
  33. public static boolean isMasterWord(String word, int[] countChars, int count) {
  34. for (int i = 0; i < word.length(); i++) {
  35. countChars[word.charAt(i) - 'a']--;
  36. if (countChars[word.charAt(i) - 'a'] < 0) {
  37. count--;
  38. // ? 不够用了直接返回false
  39. if (count < 0) {
  40. return false;
  41. }
  42. }
  43. }
  44. return true;
  45. }
  46. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/955836
推荐阅读
相关标签
  

闽ICP备14008679号