優化前的**由leetcode大佬寫,優化後是我寫的:
優化後:優化思路
例如s="efabcdabcdab", words=["ab","cd","ab"], 初始map=, 初始放置submap=;map是否與submap相等,不等,則移掉"ef", 加入"ab", "efabcd
abcdab"----》"ef
abcdab
cdab";
map是否與submap相等,此時相等,將2加入list, list=[2], 則移掉"ab", 加入"cd", "ef
abcdab
cdab"----》"efab
cdabcd
ab";
map是否與submap相等,不等,則減少掉1個"cd", 加入"ab","efab
cdabcd
ab"----》"efabcd
abcdab
";map是否與submap相等,此時相等,將6加入list, list=[2,6], 結束index=0的迴圈,
下次迴圈index=1,submap依次為藍色部分,"e
fabcda
bcdab"----》"ef
abcdab
cdab"----》"efabc
dabcda
b",都不等
index=2=乙個檔次的長度,跳出迴圈。
最終返回list=[2,6]
優化前public static listfindsubstring(string s, string words)
mapmap = new hashmap<>();
for(int i = 0; i < wordnum; i++)
for(int index = 0; index < wordlen; index++)
temp = s.substring(j+patternlen, j+patternlen+wordlen);
submap.put(temp, submap.getordefault(temp, 0)+1);
}if(submap.equals(map))
}
return list;
}
public static listfindsubstring(string s, string words)
for (int i = 0; i < s.length() - all_len + 1; i++)
if (map.equals(tmp_map)) res.add(i);//相同的時候hashmap會相等,因為hashmap就是根據hashcode實現的
}return res;
}
串聯所有單詞的子串
給定乙個字串 s 和一些長度相同的單詞 words。找出 s 中恰好可以由 words 中所有單詞串聯形成的子串的起始位置。注意 子串要與 words 中的單詞完全匹配,中間不能有其他字元,但不需要考慮 words 中單詞串聯的順序。示例 1 輸入 s barfoothefoobarman word...
演算法 串聯所有單詞的子串
給定乙個字串 s 和一些長度相同的單詞 words。找出 s 中恰好可以由 words 中所有單詞串聯形成的子串的起始位置。注意子串要與 words 中的單詞完全匹配,中間不能有其他字元,但不需要考慮 words 中單詞串聯的順序。示例 1 輸入 s barfoothefoobarman words...
Leetcode初學 串聯所有單詞的子串
我認為這道題要做出來是不難的,主要是怎麼使他的效率變高 可惜我僅僅只是將這道題做出來,深感慚愧 我的思路可以算是滑動窗體吧 因為words中的每個單詞的長度相同,所以我們已知這個長度 以這個長度作為我們窗體的長度,在s中尋找是否有在words中存在的單詞 有的話,刪除words中存在的這個單詞,繼續...