LeetCode No.28 Implement strStr()

来源:互联网 发布:java怎么使用log4j 编辑:程序博客网 时间:2024/06/04 20:39

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
找到字符串的子串位置,并返回。如果没有则返回-1
如果有兴趣,可以去研究这几个O(m+n)的算法:Rabin-Karp算法、KMP算法和Boyer-Moore算法。

public class Solution {    public int strStr(String haystack, String needle) {        int l1 = haystack.length(), l2 = needle.length();        if (l1 < l2) {            return -1;        } else if (l2 == 0) {            return 0;        }        int threshold = l1 - l2;        for (int i = 0; i <= threshold; ++i) {            if (haystack.substring(i,i+l2).equals(needle)) {                return i;            }        }        return -1;    }}
0 0