Java 6ms solution beats 91%, easy to understand


  • 0
    T

    The basic idea is not to start check at the first char but at the needle.length() - 1th char. And check backward.

    public class Solution {
        public int strStr(String haystack, String needle) {
            if(haystack.equals(needle)) return 0;
            if(needle.length() == 0) return 0;
            if(haystack.length() < needle.length()) return -1;
            int len = needle.length() - 1;
            for(int i = len; i < haystack.length(); i++){
                for(int j = i, k = len; j >= i - len ; j--, k--){
                    if(haystack.charAt(j) != needle.charAt(k)) break;
                    if(j == i - len && haystack.charAt(j) == needle.charAt(k)) return i - len;
                }
            }
            return -1;
        }
    }
    

Log in to reply
 

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