Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Subscribe to see which companies asked this question
解题思路:这道题是一个字符串在另外一个字符串中的第一个位置,相当于indexof功能,可以使用BM、KMP等算法实现,这里直接暴力解吧。
public class Solution {
public int strStr(String haystack, String needle) {
int haystacklen = haystack.length();
int needlelen = needle.length();
if(haystacklen == 0 && needlelen == 0)
{
return 0;
}
if(haystacklen<needlelen)
{
return -1;
}
int res = -1;
for(int i = 0; i < haystacklen; i++)
{
if((i + needlelen) > haystacklen)
{
return -1;
}
int j = 0;
for(; j < needlelen; j++)
{
if(haystack.charAt(i+j) != needle.charAt(j))
{
break;
}
}
if(j == needlelen)
{
res = i;
break;
}
}
return res;
}
}
本文介绍了一个简单的字符串搜索算法,该算法用于查找一个字符串(needle)在另一个字符串(haystack)中首次出现的位置。如果找到,则返回其起始索引;若未找到则返回-1。文中提供了一个Java实现示例。
540

被折叠的 条评论
为什么被折叠?



