leetcode 28. Implement strStr()

原题链接: 28. Implement strStr()

【思路】

 用 i 表示 haystack 的索引,每次对于 i,用 count 记录匹配到的最大长度,如果 count = needle 的长度,则返回 true,否则 i+1,再次进行匹配,如果都没找到,则返回 false:

    public int strStr(String haystack, String needle) {
        int len1 = haystack.length(), len2 = needle.length();
        for (int i = 0; i < len1 - len2 + 1; i++) {
            int count = 0;
            while (count < len2 && haystack.charAt(i + count) == needle.charAt(count)) count++;
            if (count == len2) return i;
        }
        return -1;
    }
72 / 72  test cases passed. Runtime: 3 ms  Your runtime beats 59.00% of javasubmissions.

你可能感兴趣的:(leetcode 28. Implement strStr())