Implement the strStr() function.
Given a haystack string and a needle string, find the first place (starting from 0) where the needle string appears in the haystack string. If not, returns - 1.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Explain:
When need is an empty string, what value should we return? This is a good question in an interview.
For this problem, we should return 0 when need is an empty string. This matches the C language's strstr() and Java's indexOf() definitions.
Method 1:
class Solution { public: int strStr(string haystack, string needle) { if(needle.empty()) return 0; if(haystack.length()<needle.length()) return -1; int flag=1,p; for(int i=0;i<haystack.length()-needle.length()+1;i++) { p=i; for(int j=0;j<needle.length();j++) { if(haystack[p++]!=needle[j])//Mismatch { flag=0; break; } flag=1;//matching } if(flag==1) return i; } return -1; } };
Method 2: use substr to get the substring with the specified length and position
class Solution { public: int strStr(string haystack, string needle) { if(needle == "") return 0; if(haystack.size() < needle.size()) return -1; int p; for(int i = 0;i < haystack.size()-needle.size()+1;++i) { if(haystack.substr(i,needle.size()) == needle) return i; } return -1; } };
Knowledge supplement:
Do this problem to know that c + + and strstr function, used to find the location of the first occurrence of a string, return a pointer.
Archetype:
const char * strstr ( const char * str1, const char * str2 ); char * strstr ( char * str1, const char * str2 );
Usage:
#include <iostream> #include <string.h> using namespace std; int main() { char *s="1234abcd"; char *sb1="34a"; int p; p=strstr(s,sb1)-s; cout<<p; return 0; }
Output 2