Implement strStr () Leetcode Java

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.