您的位置:首页 > 其它

LeetCode28. Implement strStr()

2017-06-06 11:04 323 查看

题目

Implement strStr().

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

思路

就是一个找子串的函数。

先顺势扫描,寻找首字母的匹配项,之后利用subString函数看剩余串是否匹配,如果匹配则最终返回i;寻找下一个首字母匹配位置;直到循环结束。

代码

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