LinQinの博客空间
首页项目归档照片墙音乐灵境说说杂谈友链关于
封面

LeetCode 面试经典150题

写作时间:2026-09-17 17:23:13

28. 找出字符串中第一个匹配项的下标

给你两个字符串 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 仅由小写英文字符组成

题解:

我的题解:

已发布力扣题解:https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/solutions/4030438/bao-li-shuang-zhi-zhen-zi-fu-chuan-pi-pe-qo06

class Solution {
    public int strStr(String haystack, String needle) {
        int hl= haystack.length();
        int nl = needle.length();
        if (hl<nl)  {
            return -1;
        }
        for(int i =0;i<=hl-nl;i++) {
            if(haystack.charAt(i) == needle.charAt(0) ) {
                for (int j = i,k  = 0 ; k < nl ; j++,k++) {
                    if (haystack.charAt(j) !=  needle.charAt(k)) {
                        break;
                    } 
                    if (k == nl-1) {return i;}
                }
            }
        }
        return -1;
    }
}

‍

avatar

LinQin

内陆某双非院校软件工程专业本科生,方向为后端开发,互联网边缘地带人员。

RECOMMENDED

Hello

2026-03-24 07:00:45

LeetCode 面试经典150题

2026-09-14 16:57:12

LeetCode 面试经典150题

2026-09-17 11:51:03

Table of Contents