• ​力扣解法汇总792. 匹配子序列的单词数


     目录链接:

    力扣编程题-解法汇总_分享+记录-CSDN博客

    GitHub同步刷题项目:

    https://github.com/September26/java-algorithms

    原题链接:力扣


    描述:

    给定字符串 s 和字符串数组 words, 返回  words[i] 中是s的子序列的单词个数 。

    字符串的 子序列 是从原始字符串中生成的新字符串,可以从中删去一些字符(可以是none),而不改变其余字符的相对顺序。

    • 例如, “ace” 是 “abcde” 的子序列。

     

    示例 1:

    输入: s = "abcde", words = ["a","bb","acd","ace"]
    输出: 3
    解释: 有三个是 s 的子序列的单词: "a", "acd", "ace"。
    

    Example 2:

    输入: s = "dsahjpjauf", words = ["ahjpjau","ja","ahbwzgqnuk","tnmlanowax"]
    输出: 2
    

     

    提示:

    • 1 <= s.length <= 5 * 104
    • 1 <= words.length <= 5000
    • 1 <= words[i].length <= 50
    • words[i]和 s 都只由小写字母组成。

    解题思路:

    * 解题思路:
    * 首先我们这里看复杂度,首先5W一定要遍历一遍的,其次50的长度也一定要遍历一遍的,所以我们优化的重点应该放在如何把words的5000长度优化为1。
    * 可以把s转换为一个Map>的结构,但是因为是a到z,所以使用数组更为合适。
    * 构建一个List[]类型的数组,存放的s中每个字符出现的位置集合,另外使用一个数组int[] indexs记录遍历是每个字符在List集合中使用到的位置。
    * 遍历words,依次读取每个字符,根据字符找到List集合,从集合中读取最靠前并且大于当前位置currentCharIndex的index值,
    * 找到,则继续,找不到说明不满足则退出此次循环。

    代码:

    1. public class Solution792 {
    2. public int numMatchingSubseq(String s, String[] words) {
    3. int result = 0;
    4. int[] indexs = new int[26];
    5. List<Integer>[] lists = new ArrayList[26];
    6. for (int i = 0; i < lists.length; i++) {
    7. lists[i] = new ArrayList<>();
    8. }
    9. char[] chars = s.toCharArray();
    10. for (int i = 0; i < chars.length; i++) {
    11. char aChar = chars[i];
    12. lists[aChar - 'a'].add(i);
    13. }
    14. for (String word : words) {
    15. Arrays.fill(indexs, 0);
    16. char[] wordChar = word.toCharArray();
    17. int currentCharIndex = -1;
    18. for (int i = 0; i < wordChar.length; i++) {
    19. char c = wordChar[i];
    20. int charInt = c - 'a';
    21. List<Integer> list = lists[charInt];
    22. int index = indexs[charInt];
    23. if (index >= list.size()) {
    24. break;
    25. }
    26. int oldcurrentCharIndex = currentCharIndex;
    27. while (index < list.size()) {
    28. Integer charIndex = list.get(index);
    29. index++;
    30. indexs[charInt] = index;
    31. if (charIndex >= currentCharIndex) {
    32. currentCharIndex = charIndex;
    33. break;
    34. }
    35. }
    36. //找不时,此时oldcurrentCharIndex == currentCharIndex
    37. if (currentCharIndex == oldcurrentCharIndex) {
    38. break;
    39. }
    40. if (i == wordChar.length - 1) {
    41. result++;
    42. }
    43. }
    44. }
    45. return result;
    46. }
    47. }

  • 相关阅读:
    Android 12.0 禁止二次展开QuickQSPanel设置下拉QSPanel高度
    hadoop基础
    【愚公系列】2022年11月 .NET CORE工具案例-.NET Core执行JavaScript
    1、手把手教你学会使用 FlinkSQL客户端
    深度学习面试题总结
    appendChild也是异步函数(给dom添加子节点后,第一次修改dom样式不生效)
    旧系统改造
    Shell及Linux三剑客grep、sed、awk
    Docker-Docker基本组成和架构
    普通人还有必要学习 Python 之类的编程语言吗?
  • 原文地址:https://blog.csdn.net/AA5279AA/article/details/127901320