您的位置:首页 > 编程语言 > Java开发

leetCode练习(28)

2016-09-19 19:46 260 查看
题目: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算法,目前仅知道原理,还没有实现。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode string