<?phpclass Solution { /** * @param String $s * @param String[] $words * @return Integer[] */ function findSubstring($s, $words) { $wordCount = count($words); $wordLen = strlen($words[0]); $matchLen = $wordCount * $wordLen; $map = []; $ret = []; if (!$s || !$words) { return $ret; } // 匹配字符串数量映射 foreach ($words as $v) { if (isset($map[$v])) { $map[$v]++; } else { $map[$v] = 1; } } // 迭代原字符串,查找匹配字符 for ($i = 0; $i < strlen($s) - $matchLen; $i++) { $consumeMap = $map; $iterationStr = substr($s, $i, $matchLen); // 当前已匹配字符长度 $currentLen = 0; $j = 0; while ($j < $wordCount) { $element = substr($iterationStr, $wordLen * $j, $wordLen); $j++; if (!isset($consumeMap[$element]) || $consumeMap[$element] < 1) { break; } $currentLen += $wordLen; $consumeMap[$element] = $consumeMap[$element] - 1; } if ($currentLen < $matchLen) { continue; } $ret[] = $i; } return $ret; }}$s = "barfoothefoobarman";$words = ["foo","bar"];$cls = new Solution();$r = $cls->findSubstring($s, $words);print_r($r);