Implement strStr()

lpy1990

Implement strStr()

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

思路

用双重for循环遍历, 要注意cornercase 以及两个string相比较时候指针遍历是从0到i-j 而不是i-j-1

复杂度

时间O((m-n)*n)

代码

public class Solution {

public int strStr(String haystack, String needle) {
    if (haystack == null || needle == null || haystack.length() < needle.length()) {
        return -1;
    }
    if (needle.length() == 0) {
        return 0;
    }
    for (int i = 0; i <= haystack.length() - needle.length(); i++) {
        boolean flag = true;
        for (int j = 0; j < needle.length(); j++) {
            if (haystack.charAt(i + j) != needle.charAt(j)) {
                flag = false;
                break;
            }
        }
        if (flag == true) {
            return i;
        }
    }
    return -1;
}

}

阅读 1k

26 声望
10 粉丝
0 条评论
26 声望
10 粉丝
文章目录
宣传栏