题目链接:Implement strStr()
这道题就是在字符串中找到子字符串,并返回子字符串的位置。
直观的方法,就是通过遍历对比,每次比较的长度为子字符串的长度。
代码如下:
class Solution {
public int strStr(String haystack, String needle) {
int len = haystack.length();
int sublen = needle.length();
if(sublen==0) //如果子字符串为空,则返回0
return 0;
int i=0;
for(i=0;i<=len-sublen;i++){
String sub = haystack.substring(i,sublen+i);
if(sub.equals(needle))
return i;
}
return -1;
}
}