您的位置:首页 > 其它

Leetcode28. Implement strStr()

2016-12-06 14:23 471 查看
原题

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

大意

判断字符串中是否包含另一个字符串,如果包含的话则返回字符串第一次出现的地方;如果没有包含的话,则返回-1

思路

本来想双层遍历字符串,然后去比较;后来想到字符串中的一个函数substring,可以提取某个长度的子字符串

代码

if(haystack.length()==0&&needle.length()==0) return 0;
else
for(int i=0;i<haystack.length()-needle.length()+1;i++){
String item=haystack.substring(i, i+needle.length());
if(needle.equals(item))
return i;
}
return -1;


原题地址
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  字符串