28. Implement strStr()

28. Implement strStr()_第1张图片
题目

思路:两层循环,依次遍历


public int strStr(String haystack, String needle) {
        char[] haystackArray = haystack.toCharArray();
        char[] needleArray = needle.toCharArray();
        int haystackLen = haystackArray.length;
        int needleLen = needle.length();
        if (haystackLen < needleLen) {
            return -1;
        }
        for (int i = 0; i <= haystackLen- needleLen; i++) {
            int j;
            for (j= i; j < i + needleLen; j++) {
                if (haystackArray[j] != needleArray[j-i]) break;
            }
            if (j == i + needleLen) {
                return i;
            }
        }
        return -1;
    }

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