当前位置:   article > 正文

Substring with Concatenation of All Words

substring with concatenation of all words

Substring with Concatenation of All Words

You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in wordsexactly once and without any intervening characters.

For example, given:
s"barfoothefoobarman"
words["foo", "bar"]

You should return the indices: [0,9].
(order does not matter).

滑动窗口的神题。思路和 Minimum Window Substring 非常相似。

但是这个题tricky一点在于要发现,只要遍历 string  每个单词长度(K) 遍 就可以包含全部情况。

 

几个容易出错的地方在代码中有标注。

 

这题是要求 without intervening characters的。这里跟  Minimum Window Substring 要求不同。所以就导致了再一次遍历中存在着重新初始化的情况(map初始化)

这一点应该是可以提升的,毕竟每次遇见intervening string就重启一个大的map很耗时。如果可以只修复map被污染的部分会好些。

  1. public List<Integer> findSubstring(String s, String[] words) {
  2. List<Integer> res = new ArrayList<Integer>();
  3. if (words.length == 0){
  4. return res;
  5. }
  6. int wl = words[0].length();
  7. HashMap<String, Integer> MAP = new HashMap<String, Integer>();
  8. for(String word : words){
  9. if(MAP.containsKey(word))
  10. MAP.put(word,MAP.get(word)+1);
  11. else
  12. MAP.put(word,1);
  13. }
  14. int size = words.length;
  15. for(int start=0; start<wl; start++){
  16. HashMap<String, Integer> map = new HashMap<String, Integer>(MAP);
  17. int cnt = 0;
  18. int l = start;
  19. //i<= s.length() - wl Notice the equal sign, alway try out examples to ensure it.
  20. for(int i=start; i<=s.length()-wl; i+=wl){
  21. String word = s.substring(i,i+wl);
  22. if(l > s.length() - wl*size)
  23. break;
  24. if(map.containsKey(word)){
  25. if( map.get(word) > 0){
  26. map.put(word, map.get(word)-1);
  27. cnt += 1;
  28. }else if(map.get(word) == 0){
  29. while(l<i && map.get(word) == 0){
  30. String leftWord = s.substring(l,l+wl);
  31. map.put(leftWord, map.get(leftWord)+1);
  32. cnt -= 1;
  33. l += wl;
  34. }
  35. i -= wl;
  36. }
  37. }else{
  38. l = i+wl;
  39. cnt = 0;
  40. map = new HashMap<String, Integer>(MAP);
  41. }
  42. //Notice: check cnt at the end instead of front. Otherwise can't check the instance happened at very end
  43. if(cnt == size){
  44. res.add(l);
  45. }
  46. }
  47. }
  48. return res;
  49. }

 

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

闽ICP备14008679号