LeetCode150道面试经典题--找出字符串中第一个匹配项的下标(简单)

1.题目

给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1。

2.示例


3.思路

回溯算法:首先将字符串拆分成字符数组,然后对数组进行遍历,进行一一匹配,如果出现匹配失败则回溯到一开始的数组重新进行下一次匹配。

LeetCode代码:

java 复制代码
class Solution {
    public int strStr(String haystack, String needle) {
        char hays[]=haystack.toCharArray();
        char needs[] = needle.toCharArray();
        int dex = 0;
        int count = 0;
        int j = 0;
        for (int i=0;i< hays.length;i++){
            if (hays[i] == needs[j]){
                count++;
                if (j==needs.length-1){
                    dex = i-(needs.length-1);
                    break;
                }
                j++;
                continue;
            }else { i=i-count;j = 0; count=0;}
        }
        if (count!=needs.length){
            dex = -1;
        }
        return dex;
    }
}

案例详细代码:

java 复制代码
package LeetCode09;

public class javaDemo {
    public static void main(String[] args) {
//        查找字符串第一个出现
        String haystack = "mississippi";
        String needle = "issi";
        char hays[] = haystack.toCharArray();
        char needs[] = needle.toCharArray();
//        设置计数器,初始化下脚标
        int dex = 0;
        int count = 0;
        int j = 0;
//        遍历数组
        for (int i = 0; i < hays.length; i++) {
//            判断如果当前字符匹配则往下走
            if (hays[i] == needs[j]) {
                count++;
                if (j == needs.length - 1) {
                    dex = i - (needs.length - 1);
                    break;
                }
                j++;
                continue;
            } else {
//                如果出现不匹配则进行回溯
                i=i-count;
                j = 0;
                count = 0;
            }
        }
//        判断是否有足够的count
        if (count != needs.length) {
            dex = -1;
        }
        System.out.println(dex);
    }
}

总结:

时间复杂度:n 为原串的长度,m 为匹配串的长度。其中枚举的复杂度为 O(n−m)O(n - m)O(n−m),构造和比较字符串的复杂度为 O(m)O(m)O(m)。整体复杂度为 O((n−m)∗m)O((n - m) * m)O((n−m)∗m)。

空间复杂度:O(1)O(1)O(1)。

会了?试试挑战下一题!♪(^∀^●)ノシ (●´∀`)♪

LeetCode150道面试经典题--验证回文串(简单)_Alphamilk的博客-CSDN博客


相关推荐
hetao173383722 分钟前
2026-10-22~23 hetao1733837 的刷题记录
c++·算法
yuniko-n31 分钟前
【JUC】volatile 非原子性深入解析
java
TechWayfarer35 分钟前
PHP漏洞被利用,怎么揪出攻击IP?
开发语言·python·tcp/ip·网络安全·php
java_nnnn38 分钟前
LeetCode刷题滑动窗口(串联所有单词的子串+最小覆盖的子串)Java
算法·leetcode·职场和发展
sun_weitao1 小时前
极简版 MCP 工具实现方案
java·linux·服务器
SailingCoder1 小时前
【封闭结束1】端到端交付:Agent 一次请求如何走完全链路
前端·安全·ai·面试·agent·harness
Navigator_Z1 小时前
LeetCode //C - 1301. Number of Paths with Max Score
c语言·算法·leetcode
Interview Aid1122 小时前
Uber Interview Process 完整指南:面试流程、OA 真题与 VO 备考
面试·职场和发展
金銀銅鐵2 小时前
[Java] 展示增删元素时 LinkedList 的内部变化
java·后端·ai编程
卡卡~~2 小时前
“101计划”核心课程实践教材《数据实验结构指导-C++语言版》题目集
开发语言·c++·学习·算法