题目:
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1
题解:
此题就是为了实现.indexOf();
方法一:
class Solution {
public int strStr(String haystack, String needle) {
int L = needle.length(), n = haystack.length();
for(int i = 0; i < n - L + 1; i++){
if(haystack.substring(i, i + L).equals(needle)){//substring是小写的
return i;
}
}
return -1;
}
}
方法二:其实人家就是让实现.indexOf(),所以如果知道substring 和 equals,就不要这么做了。
class Solution {
public int strStr(String haystack, String needle) {
//边界条件
if(haystack == null || needle == null){//这个题然我明白了.length()和null是不一样的
return 0;
}
return haystack.indexOf(needle);
}
}