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

LeetCode : Implement strStr() [java]

2016-03-09 00:35 483 查看
Implement strStr().

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

思路:简单遍历查找即可。

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