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

1.题目

给你两个字符串 haystackneedle ,请你在 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博客


相关推荐
洛水水5 小时前
【力扣100题】18.随机链表的复制
算法·leetcode·链表
南宫萧幕6 小时前
规则基 EMS 仿真实战:SOC 区间划分与 Simulink 闭环建模全解
算法·matlab·控制
多加点辣也没关系6 小时前
数据结构与算法|第二十三章:高级数据结构
数据结构·算法
庞轩px6 小时前
第七篇:Spring扩展点——如何优雅地介入Bean的创建流程
java·后端·spring·bean·aware·扩展点
代钦塔拉7 小时前
Qt4 vs Qt5 带参数信号槽的连接方式详解
开发语言·数据库·qt
tongluowan0078 小时前
一个请求在Spring MVC 中是怎么流转的
java·spring·mvc
hoiii1878 小时前
孤立森林 (Isolation Forest) 快速异常检测系统
算法
夜郎king8 小时前
Spring AI 对接大模型开发易错点总结与实战解决办法
java·人工智能·spring
InfinteJustice9 小时前
踩坑分享C 语言文件操作全攻略:从基础读写到随机访问与缓冲区原理
c语言·开发语言·microsoft
码云数智-大飞9 小时前
滥用Lombok的@EqualsAndHashCode导致线上事故复盘
开发语言