题意:

image.png

解题思路:

  1. 思路:
  2. 1. 滑动窗口思想
  3. 2. 每次取6个单词,每3个字符到hash中去比较,如果相等,继续搜索另外3个单词
  4. 3. 从左至右滑动窗口进行比较,比如[0-5]->[1-6]
  5. 4. 最后返回下标

PHP代码实现:

  1. class Solution {
  2. function findSubstring($s, $words) {
  3. $map = [];
  4. $ret = [];
  5. if (!$s || !$words) return $ret;
  6. //统计多少个单词
  7. $words_count = count($words);
  8. //每个单词长度
  9. $words_length = strlen($words[0]);
  10. //map: [bar => 1, foo => 1]
  11. foreach ($words as $word) ++$map[$word];
  12. //取值 0-12位 : barfoothefoobarman =》barfoothefoob
  13. for ($i = 0; $i <= strlen($s) - $words_count * $words_length; $i++) {
  14. $map_as_valid = $map;
  15. $num = 0;
  16. $j = $i;
  17. while ($num < $words_count) {
  18. //s = "barfoothefoobarman",
  19. //每次截3个=>bar,到map里面进行查找,
  20. //如果找到,则--map,总数num+1,直到num == words_count
  21. $str = substr($s, $j, $words_length);
  22. if (!isset($map_as_valid[$str]) || $map_as_valid[$str] < 1) {
  23. unset($map_as_valid);
  24. break;
  25. }
  26. $map_as_valid[$str] -= 1;
  27. $num++;
  28. //找到1个,继续到map里面找下一个=>foo
  29. $j = $j + $words_length;
  30. }
  31. //找到后记录开始下标
  32. if ($num == $words_count) {
  33. array_push($ret, $i);
  34. }
  35. }
  36. return $ret;
  37. }
  38. }

GO代码实现: