Implement strStr() LeetCode Java

來源:互聯網
上載者:User

標籤:style   class   bug   Stub   高效   toc   bst   public   arp   

描述
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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.