两个字符串haystack和needle, 返回needle第一次出现在haystack中的下标,
如果needle不是haystack的一部分,返回-1.
思路:
可以把问题 needle是不是haystack的一部分 转换为 needle和haystack的substring是否相等。
一般比较两个字符串是否相等,会先比较长度。
如果needle的长度 > haystack的长度,那必然不是它的一部分,直接返回-1.
如果长度相等,只需比较两字符串是否相等即可。
剩下的只需要解决needle长度 < haystack长度,
那就好办了,遍历haystack的下标 i, 每次取substring(i , i + needle长度) 和 needle比较,看是否相等,
一旦相等,返回 i.
i 只需要遍历到haystack长度 - needle长度即可。
public int strStr(String haystack, String needle) {
int hlen = haystack.length();
int nlen = needle.length();
if(nlen > hlen) return -1;
if(hlen == nlen) {
if(haystack.equals(needle)) return 0;
else return -1;
}
for(int i = 0; i <= hlen-nlen; i++) {
if(haystack.charAt(i) == needle.charAt(0) &&
haystack.substring(i,i+nlen).equals(needle))
return i;
}
return -1;
}