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

Leetcode-28. Implement strStr()

2016-10-02 15:42 375 查看
Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
这个题目有点略无语,其实就是实现一个字符串子串位置的算法。String已经自带这个功能了。Your runtime beats 63.74% of java submissions.
public class Solution {
public int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
}

当然这种找子串的也可以用最麻烦的两重循环O(n*m),n是haystack的长度,m是needle的长度。Your runtime beats 26.44% of java submissions.
public class Solution {
public int strStr(String haystack, String needle) {

if(haystack.length() == 0 && needle.length() == 0) return 0;
if(needle.length() == 0) return 0;
if(needle.length() > haystack.length())return -1;

for(int i = 0 ; i < haystack.length()-needle.length() + 1; i ++){
int index = i,j = 0;
boolean isSubStr = true;

while(index < haystack.length() && j < needle.length()){

if(haystack.charAt(index) != needle.charAt(j)){
isSubStr = false;
break;
}
index ++; j ++;
}

if(isSubStr && j == needle.length()) return (index - needle.length());
}
return -1;
}

}当然还有一些改进的匹配算法,比如KMP什么的,就暂时不管了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 算法 leetcode