Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll" Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba" Output: -1
题解:
1 class Solution { 2 public: 3 int strStr(string haystack, string needle) { 4 int pos = -1; 5 int len1 = haystack.size(), len2 = needle.size(); 6 for (int i = 0; i <= len1 - len2; ++i) { 7 int p1 = i, p2 = 0; 8 while (p1 < len1 && p2 < len2) { 9 if (haystack[p1] != needle[p2]) 10 break; 11 ++p1; 12 ++p2; 13 } 14 if (p2 == len2) 15 return i; 16 } 17 return -1; 18 } 19 };