顺德网站优化公司,泰安招工招聘信息,建湖人才网手机版,网站工程师简历算法-滑动窗口-串联所有单词的子串
1 题目概述
1.1 题目出处
https://leetcode.cn/problems/substring-with-concatenation-of-all-words/
1.2 题目描述 2 滑动窗口Hash表
2.1 解题思路
构建一个大小为串联子串的总长的滑动窗口为每个words中的子串创建一个hash表, 子…算法-滑动窗口-串联所有单词的子串
1 题目概述
1.1 题目出处
https://leetcode.cn/problems/substring-with-concatenation-of-all-words/
1.2 题目描述 2 滑动窗口Hash表
2.1 解题思路
构建一个大小为串联子串的总长的滑动窗口为每个words中的子串创建一个hash表, 子串值子串出现次数记录每次开始位置从左往右遍历字符串s每次截取words[0]长度的子串和2中hash表对比如果没有或者使用次数超限就表示该组合无法构成退出该次检测否则继续检测直到构成的串联子串长度满足要求或者已检测长度超限。构建成功时记录下起始序号一轮检测完成后窗口向右滑动1个长度继续下一轮检测
2.2 代码
class Solution {public ListInteger findSubstring(String s, String[] words) {ListInteger resultList new ArrayList();int windowSize words[0].length();if (windowSize s.length()) {return resultList;}int strLength windowSize * words.length;if (strLength s.length()){return resultList;}MapString, Integer wordMap new HashMap();for (int i 0; i words.length; i) {Integer subKeyTimes wordMap.get(words[i]);if (null subKeyTimes) {subKeyTimes 0;} wordMap.put(words[i], subKeyTimes 1);}for (int i 0; i s.length() - strLength; i) {int result getStart(s, words, strLength, windowSize, i, wordMap);if (result ! -1) {resultList.add(result);}}return resultList;}private int getStart(String s, String[] words, int strLength, int windowSize, int first, MapString, Integer wordMap) {int start -1;int length 0;MapString, Integer useMap new HashMap();for (int i first; i s.length() length strLength i first strLength; i windowSize) {String sub s.substring(i, i windowSize);Integer subKeyTimes wordMap.get(sub);if (null subKeyTimes) {return -1;}Integer useTimes useMap.get(sub);if (null useTimes) {useTimes 1; } else {useTimes 1;}if (useTimes subKeyTimes) {return -1;}useMap.put(sub, useTimes);length windowSize;if (start -1) {start i;}}if (length strLength) {return start;}return -1;}
}2.3 时间复杂度 s.lengthnwords.lengthm 时间复杂度O(n*m)
2.4 空间复杂度
O(m)
3 回溯法交换字符串
3.1 解题思路
3.2 代码 3.3 时间复杂度
3.4 空间复杂度
O(N)