两个字符串,需要判断第二个字符串是否为第一个字符串的子字符串,如果是的话返回子字符串所在位置第一个元素的索引
推荐解法:
KMP算法,现在还没有搞懂,已标星
当前解法:
当前为逐个比对以及回溯的方法,效率比较低,复杂度为平方
class Solution {
public int strStr(String haystack, String needle) {
if(needle.length() == 0)
return 0;
if(haystack.length() < needle.length())
return -1;
for(int i=0;i<haystack.length();i++){
if(i == haystack.length() - needle.length()+1)
break;
if(haystack.charAt(i) == needle.charAt(0)){
for(int j=0;j<needle.length();j++){
if(haystack.charAt(i+j) != needle.charAt(j))
break;
else if(j == needle.length()-1)
return i;
}
}
}
return -1;
}
}
在第一次运行代码的时候出现了字符串索引越界的情况
注意以后在使用索引的时候要留个心眼,如果索引值有可能越界,一定是要提前有所判断,比如说这里在外层循环中,如果剩余字符个数小于长度则直接break