LeetCode-028实现strStr()

80 阅读1分钟
public int strStr(String haystack, String needle) {

    if(needle==null||needle.isEmpty()){//题意为空返回0
        return 0;
    }
    if(!haystack.contains(needle)){//不包含返回-1
        return -1;
    }
    int lenH = haystack.length();
    int lenN = needle.length();

    for(int i = 0; i<lenH ;i++){

        String temp = haystack.substring(i,i+lenN);//截取haystack中与needle长度相等的字符串
        if(needle.equals(temp)){//截取到就返回
            return i;
        }

    }
    return 0;
}