码迷,mamicode.com
首页 > 编程语言 > 详细

Implement strStr() LeetCode Java

时间:2018-06-12 00:44:32      阅读:172      评论:0      收藏:0      [点我收藏+]

标签: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

标签:style   class   bug   Stub   高效   toc   bst   public   arp   

原文地址:https://www.cnblogs.com/ncznx/p/9170684.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!