题目链接:implement-strstr
/**
*
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
*
*/
public class ImplementStrStr {
// 72 / 72 test cases passed.
// Status: Accepted
// Runtime: 270 ms
// Submitted: 0 minutes ago
//暴力法 时间复杂度 O(mn) 空间复杂度o(1)
static int strStr(String haystack, String needle) {
for (int i = 0; i <= haystack.length() - needle.length(); i++) {
int j = 0;
for (; j < needle.length(); j++) {
if(needle.charAt(j) != haystack.charAt(i + j)) break;
}
if(j == needle.length()) return i;
}
return -1;
}
public static void main(String[] args) {
System.out.println(strStr("", ""));
System.out.println(strStr("a", "a"));
}
}