原题如下:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
我的代码:public class Solution {
public int strStr(String haystack, String needle) {
if(needle.length()==0)
{
return 0;
}
if(haystack.length()<needle.length())
{
return -1;
}
boolean flag = false;
int mark = -1;
for(int i =0 ;i<=haystack.length()-needle.length();i++)
{
if(needle.charAt(0)==haystack.charAt(i))
{
if(haystack.substring(i, i+needle.length()).equals(needle))
{
flag = true;
mark = i;
break;
}
}
}
return flag ? mark:-1;
}
}
本文提供了一种在Java中实现strStr()函数的方法,该函数返回needle在haystack字符串中的首次出现位置,若未找到则返回-1。通过逐字符对比的方式进行匹配,并考虑了特殊情况。
331

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



