Leetcode—— 28. Implement strStr()

本文详细解析了 LeetCode 上实现 strStr() 方法的题目,通过具体示例介绍了如何查找一个字符串在另一个字符串中首次出现的位置,并提供了简洁易懂的 Java 代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

年后第一题,身体是革命的本钱,过年没把身体照顾好,导致好多天不能学习。>_<

题目原址

https://leetcode.com/problems/implement-strstr/description/

题目描述

Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:

Input: haystack = “hello”, needle = “ll”
Output: 2

Example2:

Input: haystack = “aaaaa”, needle = “bba”
Output: -1

解题思路

这道题解题过程还是相对简单的。

  • 第一步:首先要得到两个字符串的长度
  • 第二步:嵌套for循环
    • (1) 如果needle字符串的下标值等于needle字符串的长度,就说明找到了想要返回的下标值,否则执行(2)
    • (2) 如果i+j的值等于haystack字符串的长度,那就说明没有找到想要返回的下标值,这条语句的含义就是,当haystack字符串剩余的元素个数小于needle字符串剩余元素个数,那一定没有符合条件的下标值,否则执行(3)
    • (3) 依次比较haystack字符串中的元素与needle字符串中的元素是否相等,如果不相等跳出内层循环

AC代码

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

感谢

https://leetcode.com/problems/implement-strstr/discuss/12807/Elegant-Java-solution

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值