day09 打卡28. 找出字符串中第一个匹配项的下标 459. 重复的子字符串

day09 打卡28. 找出字符串中第一个匹配项的下标 459. 重复的子字符串

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

28题目链接

1.我的思路:先用list去存储每个第一位都一样的下标。然后遍历list,for循环从记住的下标开始,对比每个字符。如果都一样的话,就是需要的下标。

class Solution {
    public int strStr(String haystack, String needle) {
        if (needle == null || haystack == null || needle.equals("")) return -1;
        List<Integer> list = new ArrayList<>();
        for (int i = 0 ; i<haystack.length() ; i++) {
            if (haystack.charAt(i) == needle.charAt(0)) {
                list.add(i);
            }
        }

        for (int i: list) {
            boolean existSame = true;
            if (needle.length() > haystack.length()-i) continue;
            for (int j = i, k=0; j<haystack.length() && k<needle.length(); j++, k++) {
                if (haystack.charAt(j) != needle.charAt(k)) {
                    existSame = false;
                    break;
                }
            }
            if (existSame) return i;
        }
        return -1;
    }
}

2.看视频的写的。视频链接

class Solution {
    public int strStr(String haystack, String needle) {
        if (needle == null || needle.length() == 0) return -1;
        int[] next = new int[needle.length()];
        getNext(next, needle);

        int j = 0;
        for (int i = 0 ; i<haystack.length() ; i++) {
            while (j>0 && needle.charAt(j) != haystack.charAt(i)) {
                j = next[j-1];
            }
            if (needle.charAt(j) == haystack.charAt(i)) {
                j++;
            }
            if (j == needle.length()) {
                return i-needle.length()+1;
            }
        }
        
        return -1;
    }

    public void getNext(int[] next, String str) {
        int j = 0 ;
        next[0] = 0;
        for (int i = 1; i<str.length() ; i++) {
            while (j>0 && str.charAt(j) != str.charAt(i)) {
                j = next[j-1];
            }
            if (str.charAt(j) == str.charAt(i)) {
                j++;
            }
            next[i] = j;
        }
    }
}

459. 重复的子字符串

459题目链接

1.移动匹配

class Solution {
    public boolean repeatedSubstringPattern(String s) {
        String str = s + s;
        return str.substring(1, str.length() - 1).contains(s);
    }
}

2.kmp不太懂

参考资料

代码随想录

posted @   zzzzzzsl  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示