zoukankan      html  css  js  c++  java
  • Leetcode-Implement strStr()

    Implement strStr().

    Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

    Update (2014-11-02):
    The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button to reset your code definition.

    Solution:

     1 public class Solution {
     2     public int strStr(String haystack, String needle) {
     3         if (haystack.length()<needle.length()) return -1;
     4         if (needle.length()==0) return 0;
     5         int len1 = haystack.length();
     6         int len2 = needle.length();
     7         for (int i=0;i<=len1-len2;i++)
     8             if (compare(haystack,i,needle))
     9                return i;
    10 
    11         return -1;
    12     }
    13 
    14     public boolean compare(String haystack, int start, String needle){
    15         for (int i=0;i<needle.length();i++){ 
    16             char c1 = haystack.charAt(start+i);
    17             char c2 = needle.charAt(i);
    18             if (c1!=c2) return false;
    19         }
    20         return true;
    21    }
    22 
    23         
    24 }

    NOTE: Seems that we can use KMP algorithm. PRACTICE IT!

  • 相关阅读:
    cd的使用
    转换器模式
    装饰模式
    策略模式
    模板方法模式
    工厂模式
    类型信息
    proto编译组件使用
    proto编译引用外部包问题
    Kafka经典三大问:数据有序丢失重复
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4129980.html
Copyright © 2011-2022 走看看