letecode [28] - Implement strStr()
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
Clarification:
What should we return when needle
is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle
is an empty string. This is consistent to C's strstr() and Java's indexOf().
题目大意:
实现函数strStr().
在字符串haystack中查找needle字符串第一次出现的位置,找到返回第一个字符出现的下标,未找到返回-1.
理 解 :
遍历字符串haystack,设置指针 i , 与needle字符串的首字符进行比较,若相等则依次比较后面的字符串。
若 与needle字符串 所有字符均相等,即needle指针j 指向末尾,即返回标记的首字符相等的位置flag。
若 仅部分字符相等,则从首字符flag后的一个字符开始重新与needle字符串比较。
代 码 C++:
class Solution { public: int strStr(string haystack, string needle) { if(needle=="") return 0; if(haystack=="") return -1; int i=0,j,flag; while(haystack[i]!='\0'){ j = 0; flag = i; while(haystack[i]!='\0' && needle[j]!='\0' && haystack[i]==needle[j]){ ++i; ++j; } if(needle[j]=='\0') return flag; if(haystack[i]=='\0') return -1; flag++; i = flag; } return -1; } };
运行结果:
执行用时 : 8 ms 内存消耗 : 8.9 MB