- 找出字符串中第一个匹配项的下标
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack的一部分,则返回 -1 。
示例 1:
输入:haystack = "sadbutsad", needle = "sad" 输出:0 解释:"sad" 在下标 0 和 6 处匹配。
第一个匹配项的下标是 0 ,所以返回 0 。 示例 2:
输入:haystack = "leetcode", needle = "leeto" 输出:-1 解释:"leeto" 没有在
"leetcode" 中出现,所以返回 -1 。
- indexOf(String str, int index):
返回从index位置开始查找指定字符str在字符串中第一次出现处的起始索引,如果此字符串中没有这样的字符,则返回 -1。
java
class Solution {
public int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
}
- 双指针解决
思路:一个指针去遍历haystack,当遇到相等的时候,去依次遍历needle看看是否全部相等,如果没有的话,继续遍历haystack
java
class Solution {
public int strStr(String haystack, String needle) {
if(needle=="") return -1;
int hlength=haystack.length();
int nlength=needle.length();
int index=-1;
for(int i=0;i<hlength;i++){
if(hlength-i<nlength)
break;
if(haystack.charAt(i)==needle.charAt(0)){
index=i;
for(int j=1;j<nlength;j++){
i++;
if(needle.charAt(j)!=haystack.charAt(i))
{ i=index;
index=-1;
break;
}
}
if(index!=-1)
break;
}
}
return index;
}
}