加快建设企业门户网站建,哈尔滨建站平台详细解读,网站开发中遇到的主要问题,手机淘宝客网站建设匹配子序列的单词数
问题描述
给定字符串 s 和一个字符串数组 words#xff0c;返回 words 中是 s 的子序列的单词数目。
子序列#xff1a;通过删除 s 中的一些字符#xff08;也可以不删除#xff09;而不改变剩余字符相对位置所形成的新字符串。
示例#xff1a;
输入:…匹配子序列的单词数问题描述给定字符串s和一个字符串数组words返回words中是s的子序列的单词数目。子序列通过删除s中的一些字符也可以不删除而不改变剩余字符相对位置所形成的新字符串。示例输入: s abcde, words [a,bb,acd,ace] 输出: 3 解释: 有三个单词是s的子序列aacdace。算法思路暴力对每个单词都从头开始在s中匹配时间复杂度O(words.length × s.length × avg_word_length)对于大量重复单词会重复计算方法预处理 二分查找为每个字符预处理其在s中的位置然后对每个单词使用二分查找多指针为每个单词维护一个指针同时遍历s缓存使用哈希表缓存已计算的结果避免重复单词的重复计算代码实现方法一预处理 二分查找importjava.util.*;classSolution{/** * 使用预处理和二分查找判断子序列 * * param s 源字符串 * param words 单词数组 * return 是s的子序列的单词数目 */publicintnumMatchingSubseq(Strings,String[]words){// 1: 预处理 - 为每个字符记录其在s中出现的所有位置ListInteger[]positionsnewList[26];for(inti0;i26;i){positions[i]newArrayList();}for(inti0;is.length();i){positions[s.charAt(i)-a].add(i);}// 2: 使用缓存避免重复计算MapString,BooleancachenewHashMap();intcount0;// 3: 对每个单词判断是否为子序列for(Stringword:words){if(cache.containsKey(word)){if(cache.get(word)){count;}continue;}booleanisSubseqisSubsequence(word,positions);cache.put(word,isSubseq);if(isSubseq){count;}}returncount;}/** * 使用二分查找判断单词是否为子序列 * * param word 待检查的单词 * param positions 字符位置预处理数组 * return true表示是子序列false表示不是 */privatebooleanisSubsequence(Stringword,ListInteger[]positions){intprevIndex-1;// 上一个匹配字符在s中的位置for(charc:word.toCharArray()){ListIntegercharPositionspositions[c-a];// 如果字符c在s中不存在直接返回falseif(charPositions.isEmpty()){returnfalse;}// 二分查找第一个大于prevIndex的位置intleft0,rightcharPositions.size();while(leftright){intmidleft(right-left)/2;if(charPositions.get(mid)prevIndex){leftmid1;}else{rightmid;}}// 如果没有找到合适的位置if(leftcharPositions.size()){returnfalse;}// 更新prevIndex为找到的位置prevIndexcharPositions.get(left);}returntrue;}}方法二多指针importjava.util.*;classSolution{/** * 使用多指针判断子序列 * 为每个单词维护一个指针同时遍历s */publicintnumMatchingSubseq(Strings,String[]words){// 使用缓存避免重复计算MapString,IntegerwordCountnewHashMap();for(Stringword:words){wordCount.put(word,wordCount.getOrDefault(word,0)1);}// 为每个唯一单词创建指针MapString,IntegerpointersnewHashMap();for(Stringword:wordCount.keySet()){pointers.put(word,0);}intmatchedCount0;// 遍历s的每个字符for(charc:s.toCharArray()){// 复制需要更新的单词列表ListStringtoRemovenewArrayList();// 检查每个单词的当前指针位置for(Stringword:pointers.keySet()){intptrpointers.get(word);if(ptrword.length()word.charAt(ptr)c){ptr;pointers.put(word,ptr);// 如果单词完全匹配if(ptrword.length()){matchedCountwordCount.get(word);toRemove.add(word);}}}// 移除已完全匹配的单词for(Stringword:toRemove){pointers.remove(word);}}returnmatchedCount;}}方法三优化二分查找importjava.util.*;classSolution{/** * 使用Collections.binarySearch优化的二分查找 */publicintnumMatchingSubseq(Strings,String[]words){// 预处理字符位置ListInteger[]positionsnewList[26];for(inti0;i26;i){positions[i]newArrayList();}for(inti0;is.length();i){positions[s.charAt(i)-a].add(i);}MapString,BooleancachenewHashMap();intcount0;for(Stringword:words){if(cache.computeIfAbsent(word,w-isSubsequenceOptimized(w,positions))){count;}}returncount;}privatebooleanisSubsequenceOptimized(Stringword,ListInteger[]positions){intprevIndex-1;for(charc:word.toCharArray()){ListIntegerlistpositions[c-a];if(list.isEmpty())returnfalse;// 使用Collections.binarySearch找到插入位置intposCollections.binarySearch(list,prevIndex1);if(pos0){pos-pos-1;// 转换为插入位置}if(poslist.size()){returnfalse;}prevIndexlist.get(pos);}returntrue;}}方法四暴力importjava.util.*;classSolution{/** * 暴力双指针使用缓存优化 */publicintnumMatchingSubseq(Strings,String[]words){MapString,BooleancachenewHashMap();intcount0;for(Stringword:words){if(cache.computeIfAbsent(word,w-isSubsequenceBrute(s,w))){count;}}returncount;}privatebooleanisSubsequenceBrute(Strings,Stringword){inti0,j0;while(is.length()jword.length()){if(s.charAt(i)word.charAt(j)){j;}i;}returnjword.length();}}算法分析时间复杂度预处理 二分查找O(s.length (word.length × log(s.length)))多指针O(s.length × unique_words_count)暴力带缓存O(s.length × unique_words_count)空间复杂度预处理 二分查找O(s.length unique_words_count)多指针O(unique_words_count × avg_word_length)暴力O(unique_words_count × avg_word_length)算法过程1s “abcde”, words [“a”,“bb”,“acd”,“ace”]预处理positions[‘a’] [0]positions[‘b’] [1]positions[‘c’] [2]positions[‘d’] [3]positions[‘e’] [4]单词检查“a”字符’a’在positions[0]中找 -1的位置 → 找到0完全匹配“bb”第一个’b’在positions[1]中找 -1的位置 → 找到1第二个’b’在positions[1]中找 1的位置 → 未找到“acd”‘a’找到位置0prevIndex0‘c’在positions[2]中找 0的位置 → 找到2prevIndex2‘d’在positions[3]中找 2的位置 → 找到3prevIndex3完全匹配“ace”‘a’找到位置0prevIndex0‘c’找到位置2prevIndex2‘e’在positions[4]中找 2的位置 → 找到4prevIndex4完全匹配结果3个单词匹配测试用例publicstaticvoidmain(String[]args){SolutionsolutionnewSolution();// 测试用例1标准示例String[]words1{a,bb,acd,ace};System.out.println(Test 1: solution.numMatchingSubseq(abcde,words1));// 3// 测试用例2重复单词String[]words2{a,a,a};System.out.println(Test 2: solution.numMatchingSubseq(abcde,words2));// 3// 测试用例3空单词String[]words3{};System.out.println(Test 3: solution.numMatchingSubseq(abcde,words3));// 1// 测试用例4无匹配String[]words4{bb,cb,bd};System.out.println(Test 4: solution.numMatchingSubseq(abcde,words4));// 0// 测试用例5完全匹配String[]words5{abcde};System.out.println(Test 5: solution.numMatchingSubseq(abcde,words5));// 1// 测试用例6长字符串StringlongSabcdefghijklmnopqrstuvwxyz;String[]words6{ace,xyz,aeiou,bcdfg};System.out.println(Test 6: solution.numMatchingSubseq(longS,words6));// 4// 测试用例7单字符sString[]words7{a,b,c};System.out.println(Test 7: solution.numMatchingSubseq(a,words7));// 1// 测试用例8大量重复单词String[]words8newString[5000];Arrays.fill(words8,ace);System.out.println(Test 8: solution.numMatchingSubseq(abcde,words8));// 5000// 测试用例9边界情况String[]words9{a,z};System.out.println(Test 9: solution.numMatchingSubseq(a,words9));// 1// 测试用例10空sString[]words10{a,};System.out.println(Test 10: solution.numMatchingSubseq(,words10));// 1 (只有空字符串匹配)}关键点缓存words数组可能包含大量重复单词缓存可以将时间复杂度从 O(total_words) 降低到 O(unique_words)二分查找预处理每个字符的位置避免重复遍历s对于长s和短单词效率提升子序列不需要连续必须保持相对顺序空字符串是任何字符串的子序列字符位置使用 ArrayList 存储每个字符的所有位置位置天然有序适合二分查找边界情况处理空字符串、单字符、重复字符等特殊情况字符在s中不存在的情况常见问题为什么需要缓存words可能包含重复单词不缓存会导致重复计算效率低下二分查找找第一个大于prevIndex的位置确保字符的相对顺序正确