题意:
解题思路:
时间复杂度:O(M*N)思路: 1. 对 haystack 的每个位置暴力匹配子串 needle; 2. 如果相等,则向后继续匹配,不等的话,子串从0开始,继续匹配; 3. 最后返回i - j的区间长度;
PHP代码实现:
class Solution { function strStr($haystack, $needle) { $i = 0; $j = 0; while (isset($haystack[$i]) && isset($needle[$j])) { if ($haystack[$i] == $needle[$j]) { $i++;$j++; } else { $i = $i - $j + 1; $j = 0; } } return $j == strlen($needle) ? ($i - $j) : - 1; }}
GO代码实现:
func strStr(haystack string, needle string) int { l1 := len(haystack) l2 := len(needle) if l2 == 0 { return 0 } if l1 == 0 || l1 < l2 { return -1 } for i := 0; i <= l1 - l2; i++ { if haystack[i : i + l2] == needle { return i } } return -1}