admin管理员组文章数量:1636897
题目链接:https://leetcode/problems/implement-strstr/
题目:implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
解题思路:题意为在字符串变量haystack找出第一次出现字符串needle的索引值,若不存在就返回-1。本意应该是让答题者自己写函数实现的,试了一下函数indexOf(),也是可以Accept的。嗯,就是这样。
示例代码:
public class Solution
{
public int strStr(String haystack, String needle)
{
return haystack.indexOf(needle);
}
}
方法二:
public class Solution
{
public int strStr(String haystack, String needle)
{
if(haystack.length()<needle.length())
return -1;
if("".equals(needle)&&"".equals(haystack))
return 0;
if("".equals(needle))
return 0;
int j=0; //needle索引
int i=0; //haystack索引
int k=0; //记录上一次相等的索引值
while((k+needle.length())<=haystack.length())
{
if(haystack.charAt(i)==needle.charAt(j))
{
i++;
j++;
if(j==needle.length())
{
return k;
}
}
else
{
j=0;
k++;
i=k;
}
}
return -1;
}
}
本文标签: OJLeetCodestrStrimplement
版权声明:本文标题:【LeetCode OJ 28】Implement strStr() 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dongtai/1729235287a1191921.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论