public class Solution {
public int strStr(String haystack, String needle) {
if(haystack == null || needle == null || needle.length() > haystack.length()) {
return -1;
}else if(haystack.equals(needle) || needle.length() == 0) {
return 0;
}
int index = -1;
boolean[][] f = new boolean[needle.length()+1][haystack.length()+1];
for(int j = 0; j < haystack.length()+1; j++) {
f[0][j] = true;
}
for(int i = 1; i <= needle.length(); i++) {
for(int j = 1; j <= haystack.length(); j++) {
if(needle.charAt(i-1) == haystack.charAt(j-1) && f[i-1][j-1]) {
f[i][j] = true;
if(i == needle.length()) {
index = j-needle.length();
break;
}
}
}
}
return index;
}
}
28. Implement strStr()
最新推荐文章于 2025-05-07 11:37:05 发布