Describe
Implement strStr ().
Returns A pointer to the first occurrence of needle in haystack, or null if needle are not part of haystack.
Analysis
The complexity of the brute force algorithm is O (M n), as shown in the code below. More efficient algorithms have KMP algorithms, boyer-mooer algorithms, and
Rabin-karp algorithm. There are plenty of brute force algorithms in the interview, so be sure to write them without bugs.
Needle is not a substring of haystack, yes then return this substring
Code
1 Public classStrinstr {2 3 Public Static voidMain (string[] args) {4 //TODO auto-generated Method Stub5String haystack = "1strstr12str";6String needle= "str"; 7 System.out.println (strStr (haystack, needle));8 9 }Ten Public Staticstring StrStr (string str,string s) { One if(str== "") { A returnstr; - } - CharKey=s.charat (0); the intIndex=0; - //int Index=str.indexof (key); - Char[] Sch=S.tochararray (); - Char[] Strch=Str.tochararray (); + - while(Index!=-1) { +index=Str.indexof (key); A for(inti=0;i<sch.length;i++) { at if(sch[i]==strch[index+i]) { - returns; - } - } -Str=str.substring (index+1); - in } - return NULL; to } +
- the * //Method Two $ Public Staticstring StrStr2 (String haystack, string needle) {Panax Notoginseng if(needle.length () = = 0) - returnhaystack; the + for(inti = 0; I < haystack.length (); i++) { A if(Haystack.length ()-i + 1 <needle.length ()) the return NULL; + - intK =i; $ intj = 0; $ - while(J < Needle.length () && K < Haystack.length () && Needle.charat (j) = =Haystack.charat (k)) { -J + +; thek++; - if(J = =needle.length ())Wuyi returnhaystack.substring (i,k); the } - Wu } - return NULL; About } $}
Implement strStr () Leetcode Java