思路:indexOf(string),注意indexof返回string出现的第一个位置,如果string不存在,返回-1。下面给出解答:
public int strStr(String haystack, String needle) {
if(needle == ""){ //当needle为空字符时,返回0;
int i = 0;
return i ;
}else{
return haystack.indexOf(needle);
}
}
总结:
- 为什么needle为空是要返回0,我觉得是因为空集是任何集合的子集。
- 熟练使用string.indexOf(string)