Java solution similar String.indexOf()


  • 0
    D

    similar java index of

        public int strStr(String haystack, String needle) {
            if (needle.length() > haystack.length()) {
                return -1;
            }
            if (haystack.length() == needle.length() && haystack.equals(needle)) {
                return 0;
            }
            if (needle.length() <= 0) {
                return 0;
            }
            char[] strs = haystack.toCharArray();
            char[] search = needle.toCharArray();
            int max = strs.length - needle.length();
            for (int i = 0; i <= max; i++) {
                if (strs[i] == search[0]) {
                    for (int j = i, k = 0; k < search.length && j < strs.length; j++, k++) {
                        if (strs[j] != search[k]) {
                            break;
                        }
                        if (k == search.length - 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.