您的位置:首页 > 其它

LeetCode-- Implement strStr()

2017-09-24 11:51 357 查看
题目:

Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
解读:給字符串haystack和字符串needle,找到haystack中第一次出现needle的位置下标并返回。
代码:class Solution {
public int strStr(String haystack, String needle) {

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