Implement strStr()

Implement strStr().

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

public int strStr(String haystack, String needle) {
        if(haystack==null||needle==null||needle.length()==0){
            return 0;
        }
        if (needle.length()>haystack.length()){
            return -1;
        }
        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){
                return i;
            }
        }
        return -1;
    }
posted @ 2017-10-11 13:07  binryang  阅读(60)  评论(0编辑  收藏  举报