要求:
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = “hello”, needle = “ll”
输出: 2
示例 2:
输入: haystack = “aaaaa”, needle = “bba”
输出: -1
1.常规解法
class Solution {
public int strStr(String haystack, String needle) {
if(needle.equals("")) {
return 0;
}
if(haystack.equals("") && !needle.equals("")) {
return -1;
}
//char f = needle.charAt(0);
for(int i = 0;i < haystack.length();i++) {
//char tem = haystack.charAt(i);
if(haystack.charAt(i) == needle.charAt(0)) {
//String t = haystack.substring(i);
//这里如果不用startWith的话,写个循环依次判断一下
if(haystack.substring(i).startsWith(needle)) {
return i;
}
}
}
return -1;
}
}
2.很6的解法
class Solution {
public int strStr(String haystack, String needle) {
//直接返回indexOf函数的返回值就ok
return(haystack.indexOf(needle));
}
}
“`