您的位置:首页 > 其它

[LeetCode]Implement strStr()

2017-07-13 07:59 405 查看
Description:

Implement strStr().

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

解析:

这是算法中比较经典的问题,判断一个字符串是否是另一个字符串的子串。这个题目最经典的算法应该是KMP算法,不熟悉的朋友可以参见Knuth–Morris–Pratt algorithm。KMP算法是最优的线性算法,复杂度已经达到这个问题的下限。但是KMP算法比较复杂,很难在面试的短时间里面完整正确的实现。所以一般在面试中并不要求实现KMP算法。

下面我们先说说brute force的算法,假设原串的长度是n,匹配串的长度是m。思路很简单,就是对原串的每一个长度为m的字串都判断是否跟匹配串一致。总共有n-m+1个子串,所以算法时间复杂度为O((n-m+1)*m)=O(n*m),空间复杂度是O(1)。

code:

public int strStr(String haystack, String needle) {
int m = haystack.length();
int n = needle.length();
if(m<n)return -1;
if(n==0)return 0;
int length = m-n+1;
for(int i=0;i<length;i++){
if((haystack.substring(i,n)).equals(needle)){
return i;
}
n++;
}
return -1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode