您的位置:首页 > 其它

[Leetcode] 28. Implement strStr()

2015-03-14 03:36 260 查看
Implement strStr().

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

有空还是要熟悉一下KMP

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