1. 程式人生 > >Implement strStr() LeetCode Java

Implement strStr() LeetCode Java

ner AC ray args array n-k ID out stub

描述
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
分析
暴力算法的復雜度是 O(m ? n),代碼如下。更高效的的算法有 KMP 算法、Boyer-Mooer 算法和
Rabin-Karp 算法。面試中暴力算法足夠了,一定要寫得沒有 BUG。

needle是不是haystack的子串,是的話就返回這個子串

代碼

 1 public class StrInStr {
 2 
 3     public
static void main(String[] args) { 4 // TODO Auto-generated method stub 5 String haystack ="1strSTR12str"; 6 String needle="str"; 7 System.out.println(strStr(haystack ,needle)); 8 9 } 10 public static String strStr(String str,String s) { 11 if (str=="") {
12 return str; 13 } 14 char key=s.charAt(0); 15 int index=0; 16 // int index=str.indexOf(key); 17 char[] sch=s.toCharArray(); 18 char[] strch=str.toCharArray(); 19 20 while(index!=-1) { 21 index=str.indexOf(key); 22 for
(int i=0;i<sch.length;i++) { 23 if(sch[i]==strch[index+i]) { 24 return s; 25 } 26 } 27 str=str.substring(index+1); 28 29 } 30 return null; 31 } 32




33 34 35 //方法二 36 public static String strStr2(String haystack, String needle) { 37 if (needle.length() == 0) 38 return haystack; 39 40 for (int i = 0; i < haystack.length(); i++) { 41 if (haystack.length() - i + 1 < needle.length()) 42 return null; 43 44 int k = i; 45 int j = 0; 46 47 while (j < needle.length() && k < haystack.length() && needle.charAt(j) == haystack.charAt(k)) { 48 j++; 49 k++; 50 if (j == needle.length()) 51 return haystack.substring(i,k); 52 } 53 54 } 55 return null; 56 } 57 }

Implement strStr() LeetCode Java