题意:
解题思路:
思路:
1. 滑动窗口思想
2. 每次取6个单词,每3个字符到hash中去比较,如果相等,继续搜索另外3个单词
3. 从左至右滑动窗口进行比较,比如[0-5]->[1-6]
4. 最后返回下标
PHP代码实现:
class Solution {
function findSubstring($s, $words) {
$map = [];
$ret = [];
if (!$s || !$words) return $ret;
//统计多少个单词
$words_count = count($words);
//每个单词长度
$words_length = strlen($words[0]);
//map: [bar => 1, foo => 1]
foreach ($words as $word) ++$map[$word];
//取值 0-12位 : barfoothefoobarman =》barfoothefoob
for ($i = 0; $i <= strlen($s) - $words_count * $words_length; $i++) {
$map_as_valid = $map;
$num = 0;
$j = $i;
while ($num < $words_count) {
//s = "barfoothefoobarman",
//每次截3个=>bar,到map里面进行查找,
//如果找到,则--map,总数num+1,直到num == words_count
$str = substr($s, $j, $words_length);
if (!isset($map_as_valid[$str]) || $map_as_valid[$str] < 1) {
unset($map_as_valid);
break;
}
$map_as_valid[$str] -= 1;
$num++;
//找到1个,继续到map里面找下一个=>foo
$j = $j + $words_length;
}
//找到后记录开始下标
if ($num == $words_count) {
array_push($ret, $i);
}
}
return $ret;
}
}
GO代码实现: