28. Implement strStr()

Descritpion

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Note: haystack的意思是干草堆。题意为大海捞针 LOL~

Solution

Basic

Brute-force

public class Solution {
    public int strStr(String haystack, String needle) {
        if (haystack == null || needle == null) {
            return -1;
        }
        
        int hl = haystack.length();
        int nl = needle.length();
        int j = 0;
        
        for (int i = 0; i <= hl - nl; ++i) {
            for (j = 0; j < nl && haystack.charAt(i + j) == needle.charAt(j); ++j) { }
            if (j == nl) return i;
        }
        
        return -1;
    }
}

TODO: Optimisation

KMP

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容