点击标题可直达LeetCode对应的题页
题目原文
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。
思路
内置函数代码
1 2 3 4 5 6
| class Solution { public: int strStr(string haystack, string needle) { return haystack.find(needle); } };
|
暴力匹配代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| int strStr(char * haystack, char * needle){ char *p = haystack; char *q = needle;
while(*p != '\0') { if(*p == *q) { char* tmp_p = p; char* tmp_q = q; int start = p - haystack; while(*tmp_q != '\0') { if(*tmp_p != *tmp_q || *tmp_p == '\0') { break; } tmp_p++; tmp_q++; } if(*tmp_q == '\0') { return start; } } p++; } return -1; }
|
更简洁的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| int strStr(char * haystack, char * needle) { for(int i = 0;haystack[i] != '\0'; i++) { int j = 0; while(needle[j] != '\0' && haystack[i+j] != '\0' && haystack[i+j] == needle[j]) { j++; }
if(needle[j] == '\0') { return i; } } return -1; }
|