水题
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll" Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba" Output: -1
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().
class Solution {
public int strStr(String haystack, String needle) {
int lenA=haystack.length();
int lenB=needle.length();
if(lenA<lenB)
return -1;
int index=0;
while(true){
String str=haystack.substring(index,index+lenB);
if(needle.equals(str))
return index;
index++;
if((index+lenB)>lenA)
break;
}
return -1;
}
}
本文提供了一个字符串匹配算法的具体实现,该算法用于寻找一个字符串(haystack)中另一个字符串(needle)首次出现的位置。若找到则返回该位置的索引,否则返回-1。文章通过示例展示了如何使用该算法,并对特殊情况进行了说明。
510

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



