题目描述:
代码如下(附有解析):
class Solution {
public int strStr(String haystack, String needle) {
//如果为空直接返回0
if(needle.equals("")){
return 0;
}
//如果haystack长度小于needle直接返回-1
if(haystack.length()>=needle.length()){
for(int i=0;i<haystack.length();i++){
//判断第一个字符是否相等
if(haystack.charAt(i)==needle.charAt(0)){
//若从i位置开始haystack往后的长度小于needle直接返回-1
if(haystack.substring(i).length()<needle.length()){
return -1;
}
//若从i位置开始haystack与needle相等,直接返回i
if(haystack.substring(i,needle.length()+i).equals(needle)){
return i;
}
}
}
return -1;
}
return -1;
}
}