题目
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例
示例 1:
输入: haystack = “hello”, needle = “ll”
输出: 2
示例 2:
输入: haystack = “aaaaa”, needle = “bba”
输出: -1
思路
暴力解法:两个字符串,逐个对比字符,相同时返回
public int strStr(String haystack, String needle) {
if(needle.isEmpty()){
return 0;
}
if(haystack.isEmpty() || haystack.length()<needle.length()){
return -1;
}
int slow=-1;
for(int i=0;i<haystack.length();i++){
if(haystack.charAt(i)==needle.charAt(0)){
slow=i;
for(int j =0;j<needle.length();j++){
if(haystack.length()-1<i+j){
return -1;
}
if(haystack.charAt(i+j)!=needle.charAt(j)){
slow=-1;
break;
}
if(j==needle.length()-1){
return slow;
}
}
}
}
return slow;
}
优化思路
public int strStr(String haystack, String needle) {
if(""==needle){
return 0;
}
return haystack.indexOf(needle);
}