一、LeetCode实现 strStr()
题目描述:
给你两个字符串 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 。
作者:力扣 (LeetCode)
链接:https://leetcode.cn/leetbook/read/top-interview-questions-easy/xnr003/
来源:力扣(LeetCode)
二、使用步骤
1.运行结果
2.代码
class Solution {
public int strStr(String haystack, String needle) {
int len1 = haystack.length();
int len2 = needle.length();
if(len2 > len1)
return -1;
// i表示从主串的哪个位置开始匹配
int i = 0;
//index1 表示haystack 每次匹配子串的下标
//index2 表示needle 每次匹配的下标
int index1 = 0,index2 = 0;
while(i < len1){
index1 = i;
while(index2 < len2 && index1 < len1){
if(haystack.charAt(index1) == needle.charAt(index2)){
index1 ++;
index2 ++;
}else{
index2 = 0;
break;
}
}
if(index2 == len2){
return i;
}
i++;
}
return -1;
}
}