题目描述:Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
中文理解:实现获取某一字符串needle 在给定字符串haystack的起始下标,如aaa在aabaaa的起始下标为3。同时尽量不要使用java或者c++已有的函数来实现。
解题思路:可以可以首先根据needle和haystack的长度来进行分类,若needle为空则返回0;若needle长度大于haystack返回-1;若长度相等且字符串相等,则返回0;否则haystack长度大于needle,则在haystack从下表为0开始遍历直到最后一个可以构成needle长度的下标截止,判断从该下标取出的字符串是否等于needle,等则返回该下标,否则继续。最后返回-1;
代码(java):
class Solution {
public int strStr(String haystack, String needle) {
int haystackLength=haystack.length();
int needleLength=needle.length();
if (needleLength==0)return 0;
if (haystackLength<needleLength)return -1;
else if (haystackLength==needleLength && haystack.equals(needle))return 0;
else{
for(int i=0;i<=haystackLength-needleLength;i++){
if(haystack.substring(i,i+needleLength).equals(needle)){
return i;
}
}
}
return -1;
}
}