这道题我第一反应就是indexOf函数,我使用了,直接通过,6ms。
算法我也是看了看答案,脑袋昏沉沉,没动脑想,不过理解了
------------------------------------------------------------------------------
class Solution {
public int strStr(String haystack, String needle) {
if(needle.equals("")) return 0;
if(haystack.length() < needle.length()) return -1;
int tag = haystack.length() - needle.length();
for(int i = 0;i <= tag;i++){
if(haystack.substring(i,i + needle.length()).equals(needle)){
return i;
}
}
return -1;
1.先判断子串是否为空,空的话返回0;
2.当子串大于haystack,返回负一
3.主要是tag变量,用于防止下标越界
4.index从i开始遍历,每次遍历长度为needle的长度,i++的比较每一位
5.当i=tag时,证明比较到最后面了,i+needle.length=haystack.length