解题思路
- 在母串中先定位到子串首字符的位置
- 从该位置开始截取与子串长度相同的字符串
- 用截取的字符串与字串进行对比
- 如果相同就返回该位置的索引,如果不同循环以上步骤
解题方法
- 首先通过母串和子串的长度进行判断,如果子串的长度大于母串的长度,直接返回-1
- 如果子串长度小于母串长度,获取子串首字母第一次出现的索引值并记录
- 在母串中截取从该位置到该位置+子串长度的字符串
- 对比截取字符串与子串,如相同,则返回先前记录的索引值;如不相同,获取第二次出现的索引,一次递归直至循环结束或找到相同字符串
- 如果循环结束仍为出现相同字符串,返回-1
实现代码
class Solution {
public int strStr(String h, String n) {
int hlength = h.length();
int nlength = n.length();
if (nlength > hlength) {
return -1;
} else {
int index = -1;
for (int i = 0; i < h.length(); i++) {
if (h.charAt(i) == n.charAt(0)) {
if(i+nlength<=hlength) {
String str = h.substring(i, i + nlength);
if (str.equals(n)) {
index = i;
break;
}
}else {
return -1;
}
}
}
return index;
}
}
}