2022.03.24(LC_28_实现 strStr())

该博客主要探讨了两种暴力匹配算法的实现方式,用于在一个字符串中查找另一个子串首次出现的位置。这两种方法都遍历了主字符串,并检查每个起始位置是否能完全匹配目标子串。当找到匹配时返回起始索引,否则返回-1。

方法:暴力匹配

class Solution {
    public int strStr(String haystack, String needle) {
        if (needle == null || needle.length() == 0) {
            return 0;
        }
        int hLen = haystack.length(), nLen = needle.length();
        for (int index = 0; index <= hLen - nLen; index++) {
            if (haystack.charAt(index) != needle.charAt(0)) {
                continue;
            }
            int ans = index;
            int i = index;
            int j = 0;
            while (i < hLen && j < nLen && haystack.charAt(i) == needle.charAt(j)) {
                i++;
                j++;
            }
            if (j == needle.length()) {
                return ans;
            }
        }
        return -1;
    }
}
class Solution {
    public int strStr(String haystack, String needle) {
        int m = haystack.length(), n = needle.length();
        for (int i = 0; i <= m - n; i++) {
            boolean flag = true;
            for (int j = 0; j < n; j++) {
                if (haystack.charAt(i + j) != needle.charAt(j)) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                return i;
            }
        }
        return -1;
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值