leetCode-28: 实现 strStr()

题目描述:

实现 strStr() 函数。

给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回  -1 。

说明:

当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。

对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。

示例1:

输入:haystack = "hello", needle = "ll"
输出:2

示例2:

输入:haystack = "aaaaa", needle = "bba"
输出:-1

示例3:

输入:haystack = "", needle = ""
输出:0

解题1:暴力法。将母串 heystack 和子串 needle 分别转换成数组,然后使用双层循环去逐个比较两个串中的元素,如果 heystack[i] == needle[j],再去判断 heystack[i + 1] 是否等于 needle[j + 1],直到将子串比较完毕,如果符合,直接返回 i 即可。

代码如下:

public static int strStr(String haystack, String needle) {
    char[] haystackArray = haystack.toCharArray();
    char[] needleArray = needle.toCharArray();
    for (int i = 0; i <= haystackArray.length - needleArray.length; i++) {
        int j;
        for (j = 0; j < needleArray.length; j++) {
            if (haystackArray[i + j] != needleArray[j]) {
                break;
            }
        }
        if (j == needleArray.length) {
            return i;
        }
    }
    return -1;
}

假设母串 heystack = "hello",子串needle = "ll",其循环过程如下:

第一次:i = 0,j = 0,heystack[i] = 'h',needle[j] = 'l',heystack[i + j] != needle[j],break 跳出内层循环,此时 j != needle.length,进入第二次循环

第二次:i = 1,j = 0,heystack[i] = 'e',needle[j] = 'l',heystack[i + j] != needle[j],break 跳出内层循环,此时 j != needle.length,进入第三次循环

第三次:i = 2,j = 0,heystack[i] = 'l',needle[j] = 'l',heystack[i + j] == needle[j],继续内层循环,j 自增 1,needle[j] = 'l',heystack[i + j] == needle[j],继续去内层循环,此时 j 自增 1 之后等于 2,不满足内层循环条件,所以退出内层循环,此时 j == needle.length,即找到了子串在母串中的位置了,直接 return 即可

解题2:双指针法。基本思路和暴力解法一样。

代码如下:

public static int strStr2(String haystack, String needle) {
    if (needle.length() == 0) {
        return 0;
    }
    int left = 0, right = 0, index = 0;
    while (right < haystack.length() && index < needle.length()) {
        if (haystack.charAt(right) != needle.charAt(index)) {
            left++;
            right = left;
            index = 0;
        } else {
            right++;
            index++;
        }
    }
    return index == needle.length() ? left : -1;
}

解题3:直接使用 str.indexOf() 方法

public static int strStr3(String haystack, String needle) {
    return haystack.indexOf(needle);
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值