Content-Length: 209791 | pFad | http://github.com/youngyangyang04/leetcode-master/issues/2939

FA 实现“strStr()”新增算法竞赛版本 · Issue #2939 · youngyangyang04/leetcode-master · GitHub
Skip to content

实现“strStr()”新增算法竞赛版本 #2939

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
zerd1y opened this issue May 16, 2025 · 0 comments
Open

实现“strStr()”新增算法竞赛版本 #2939

zerd1y opened this issue May 16, 2025 · 0 comments

Comments

@zerd1y
Copy link

zerd1y commented May 16, 2025

感觉算法竞赛版本的KMP算法更加精简,更好理解
采用字符串拼接方法,只需找到pi[i] == m的位置
附上解释链接:https://oi-wiki.org/string/kmp/

class Solution {
    public int strStr(String haystack, String needle) {
        int n = haystack.length();
        int m = needle.length();
        String s = needle + "#" + haystack;
        int[] pi = new int[s.length()];

        for (int i = 1; i < s.length(); i++) {
            int len = pi[i - 1];
            while (len > 0 && s.charAt(i) != s.charAt(len)) {
                len = pi[len - 1];
            }
            if (s.charAt(i) == s.charAt(len)) {
                pi[i] = len + 1;
                if (pi[i] == m) {
                    return i - m * 2;
                }
            }
        }
        return -1;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant








ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: http://github.com/youngyangyang04/leetcode-master/issues/2939

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy