zoukankan      html  css  js  c++  java
  • Implement strStr() LeetCode Java

    描述
    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 }
  • 相关阅读:
    Table的基本操作
    MySQL数据库基本操作
    jmeter中服务器返回的cookies的查看
    jemeter的乱码问题
    cucumber的报告
    Cucumber的依赖
    idea里maven执行插件pom文件依赖设置
    Tomcat和jenkins的安装
    maven配置
    Ajax必知必会
  • 原文地址:https://www.cnblogs.com/ncznx/p/9170684.html
Copyright © 2011-2022 走看看