* 问题标题:找出字符串中第一个匹配项的下表 * 题意说明: * 给你两个字符串 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 。 * * 提示: * 1 <= haystack.length, needle.length <= 104 * haystack 和 needle 仅由小写英文字符组成 * * Related Topics * 双指针 * 字符串 * 字符串匹配
public class StrStr_0009 {
public static void main(String[] args) {
}
public int strStr(String haystack, String needle) {
return 0;
}
}
使用双指针:
package com.czxy; /** * @ClassName StrStr_0009 * @Author cheng * @Description 问题标题:找出字符串中第一个匹配项的下表 * 题意说明: * 给你两个字符串 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 。 * * 提示: * 1 <= haystack.length, needle.length <= 104 * haystack 和 needle 仅由小写英文字符组成 * * Related Topics * 双指针 * 字符串 * 字符串匹配 * * @Date 2023/8/4 9:53 * @Version 1.0 */ public class StrStr_0009 { public static void main(String[] args) { String haystack = "sadbutsad"; String needle="sad"; System.out.println(strStr(haystack,needle)); } public static int strStr(String haystack, String needle) { // 用来记录满足条件的下标 int ind = -1; // 记录相等字符串长度 int count = 0; // 判断是否包含该字符串 if(haystack.contains(needle)) { for (int i = 0; i < haystack.length(); i++) { for (int j = 0; j < needle.length(); j++) { // 从第一个字符串的位置开始判断之后每个字符是否相等,相等则记录相等数量 count 并且结束当前循环 if (i + j < haystack.length() && haystack.charAt(i + j) == needle.charAt(j)) { count++; continue; } } // 判断count 是否与要比较的字符串长度相等 if (count == needle.length()) { // 相等则记录该字符第一个位置下标 ind = i; // 结束程序 break; } else { // 没有找到匹配字符串 ind = -1; // 重置count count = 0; } } } return ind; } }