[LeetCode] 28. Implement strStr()

19 篇文章 0 订阅
9 篇文章 0 订阅

原题链接:https://leetcode.com/problems/implement-strstr/

1. 题目介绍

Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
实现函数strStr()
needle字符串是模式字符串,haystack是主字符串,如果主字符串包含模式字符串,那么返回主串中模式字符串的首字符的下标,如果主串中不包含模式字符串,那么返回-1

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

Clarification:
说明
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().
当needle字符串为空时,我们应该返回什么值呢?如果在面试中,这是一个很好的问题。
对于这道题来说,当needle字符串为空时,我们将要返回0。这样做能够和C语言的strstr()函数、Java语言的indexOf()函数保持一致。

2. 解题思路

暴力搜索

时间复杂度 O ( ( m − n ) n ) O((m-n)n) O((mn)n),m 是主字符串,n 是模式字符串。

class Solution {
    public int strStr(String haystack, String needle) {
        int n_length = needle.length();
        int h_length = haystack.length();
        if(n_length == 0 ){
            return 0;
        }
        
        for(int i = 0; i < h_length-n_length+1 ; i++){
            if(haystack.substring(i,i+n_length).equals(needle)==true){
                return i;
            }
        }
        return -1;
    }
}

以下方法来自 https://leetcode-cn.com/problems/implement-strstr/solution/kmpsuan-fa-shi-xian-by-phantom_eve/ ,感兴趣的读者可以去看原文

另一种暴搜的方法:

设置两个指针 i 和 j ,分别用于指向主串(haystack)和模式串(needle)
从左到右开始一个个字符匹配。
如果主串和模式串的两字符相等,则 i 和 j 同时后移,比较下一个字符。也即是 i++,j++
如果主串和模式串的两字符不相等,就需要将模式串向右移动,也即是i 跳回去(i = i - j + 1),j 指针归零(j = 0)
所有字符匹配结束后,如果模式串指针指到串尾(j = needle.length),说明完全匹配,此时模式串在主串中,第一个字符出现的位置为:i - j

class Solution {
    public int strStr(String haystack, String needle) {
        char [] h = haystack.toCharArray();
        char [] n = needle.toCharArray();
        int h_length = h.length;
        int n_length = n.length;
        
        int i = 0;
        int j = 0;
        while(i < h_length && j < n_length){
            if(h[i] == n[j]){
                i++;
                j++;
            }else{
                i = i-j+1;
                j = 0;
            }
        }
        if(j == n_length){
            return i-j;
        }else{
            return -1;
        }
    }
}

3. 参考资料

https://leetcode-cn.com/problems/implement-strstr/solution/shi-xian-strstr-by-powcai/
https://leetcode-cn.com/problems/two-sum/solution/kmpsuan-fa-shi-xian-by-phantom_eve/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值