1. <?php
    2. class Solution {
    3. /**
    4. * @param String $s
    5. * @param String[] $words
    6. * @return Integer[]
    7. */
    8. function findSubstring($s, $words) {
    9. $wordCount = count($words);
    10. $wordLen = strlen($words[0]);
    11. $matchLen = $wordCount * $wordLen;
    12. $map = [];
    13. $ret = [];
    14. if (!$s || !$words) {
    15. return $ret;
    16. }
    17. // 匹配字符串数量映射
    18. foreach ($words as $v) {
    19. if (isset($map[$v])) {
    20. $map[$v]++;
    21. } else {
    22. $map[$v] = 1;
    23. }
    24. }
    25. // 迭代原字符串,查找匹配字符
    26. for ($i = 0; $i < strlen($s) - $matchLen; $i++) {
    27. $consumeMap = $map;
    28. $iterationStr = substr($s, $i, $matchLen);
    29. // 当前已匹配字符长度
    30. $currentLen = 0;
    31. $j = 0;
    32. while ($j < $wordCount) {
    33. $element = substr($iterationStr, $wordLen * $j, $wordLen);
    34. $j++;
    35. if (!isset($consumeMap[$element]) || $consumeMap[$element] < 1) {
    36. break;
    37. }
    38. $currentLen += $wordLen;
    39. $consumeMap[$element] = $consumeMap[$element] - 1;
    40. }
    41. if ($currentLen < $matchLen) {
    42. continue;
    43. }
    44. $ret[] = $i;
    45. }
    46. return $ret;
    47. }
    48. }
    49. $s = "barfoothefoobarman";
    50. $words = ["foo","bar"];
    51. $cls = new Solution();
    52. $r = $cls->findSubstring($s, $words);
    53. print_r($r);