Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Solution { public: int strStr(string haystack, string needle) { int len1 = haystack.length(); int len2 = needle.length(); if(len2 == 0) return 0; for(int i = 0; i <= len1 - len2; i++) { for(int j = 0; j < len2 && needle[j] == haystack[i + j]; j++) { if(j == len2 - 1) return i; } } return -1; } }; |
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼