leetCode练习(28)

来源:互联网 发布:美林时钟理论知乎 编辑:程序博客网 时间:2024/05/16 09:37

题目:Implement strStr()

难度:easy

问题描述:

Implement strStr().

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

解题思路:

最简单的是暴力子字符串查找算法,在文本中任意一个可能出现匹配的地方检测是否匹配。代码如下:

public class Solution {    public int strStr(String haystack, String needle) {       if(needle==null||haystack==null)return -1;        int len=haystack.length();        int slen=needle.length();        if(slen>len)return -1;        if(!haystack.equals("")&&needle.equals(""))return 0;        if(haystack.equals(needle))return 0;        int i,j;        for(i=0,j=0;i<len&&j<slen;i++){     //   System.out.println("i="+haystack.charAt(i)+" j="+needle.charAt(j));        if(haystack.charAt(i)==needle.charAt(j))        {        j++;   //     System.out.println("j="+j);        }        else{        i=i-j;        j=0;        }        }        if(j==slen){        return i-slen;        }        else return -1;      }}
更为优秀的是著名的KMP算法,目前仅知道原理,还没有实现。

0 0