简单题朴素做法重拳出击
kmp还没学 嘻嘻
class Solution {
public int strStr(String haystack, String needle) {
int m = haystack.length();
int n = needle.length();
for(int i = 0; i + n <= m; i ++){
boolean flag = true;
for(int j = 0; j < n; j ++){
if(haystack.charAt(i + j) != needle.charAt(j)){
flag = false;
break;
}
}
if(flag) {
return i ;
}
}
return -1;
}
}
这是kmp 我懂思想 写不出来 感谢官方题解
class Solution {
public int strStr(String haystack, String needle) {
int n = haystack.length(), m = needle.length();
if (m == 0) {
return 0;
}
int[] pi = new int[m];
for (int i = 1, j = 0; i < m; i++) {
while (j > 0 && needle.charAt(i) != needle.charAt(j)) {
j = pi[j - 1];
}
if (needle.charAt(i) == needle.charAt(j)) {
j++;
}
pi[i] = j;
}
for (int i = 0, j = 0; i < n; i++) {
while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {
j = pi[j - 1];
}
if (haystack.charAt(i) == needle.charAt(j)) {
j++;
}
if (j == m) {
return i - m + 1;
}
}
return -1;
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)