simple and easy to read.


  • 0
    X
    public int strStr(final String haystack, final String needle) {
        if (haystack == null || needle == null || needle.length() > haystack.length()) {
            return -1;
        } else if (needle.length() == 0) {
            return 0;
        }
    
        final char[] chs1 = haystack.toCharArray();
        final char[] chs2 = needle.toCharArray();
    
        for (int i = 0, to = chs1.length - chs2.length + 1; i < to; i++) {
            for (int j = 0, len = chs2.length; j < len; j++) {
                if (chs1[i + j] != chs2[j]) {
                    break;
                } else if (j == len - 1) {
                    return i;
                }
            }
        }
    
        return -1;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.