1. <?php
    2. class Solution {
    3. /**
    4. * s = "barfoothefoobarman"
    5. * words = ["foo", "bar"]
    6. * barfoo 和 foobar 满足
    7. *
    8. * @param $s
    9. * @param $words
    10. * @return array
    11. */
    12. public function findSubstring($s, $words) {
    13. $map = [];
    14. $ret = [];
    15. if (!$s || !$words) return $ret;
    16. $wordsCount = count($words);
    17. $wordsLength = strlen($words[0]);
    18. foreach ($words as $word) {
    19. $map[$word] = isset($map[$word]) ? $map[$word] + 1 : 1;
    20. }
    21. for ($i = 0; $i <= strlen($s) - $wordsCount * $wordsLength; $i++) {
    22. $tmpMap = $map;
    23. $had = 0;
    24. while($had < $wordsCount) {
    25. $str = substr($s, $i + $had * $wordsLength, $wordsLength);
    26. echo $str . "\t";
    27. if (!isset($tmpMap[$str]) || $tmpMap[$str] < 1) {
    28. break;
    29. }
    30. $tmpMap[$str] -= 1;
    31. $had++;
    32. }
    33. if ($had == $wordsCount) {
    34. $ret[] = $i;
    35. }
    36. }
    37. return $ret;
    38. }
    39. }
    40. $s = "barfoothefoobarman";
    41. $words = ["foo", "bar"];
    42. $cls = new Solution();
    43. $r = $cls->findSubstring($s, $words);
    44. print_r($r);