Sharing my JAVA solution


  • 0
    I
    public class Solution {
    public int strStr(String haystack, String needle) {
        if(haystack == null || needle == null) return -1;
        int hayLen = haystack.length();
        int neeLen = needle.length();
        if(hayLen < neeLen) return -1;
        if(neeLen==0) return 0;
        int cur = 0;
        while(cur <= hayLen-neeLen){
            int i=cur, j=0;
            while(j < neeLen){
                if(haystack.charAt(i)==needle.charAt(j)){
                    if(j == neeLen-1) return cur;
                    i++;
                    j++;
                }else{
                    break;
                }
            }
            cur++;
        }
        return -1;
    }
    

    }

    Basically I check every character in haystack until it is the same with the first char of needle, then check if the whole needle occurs. Its brute force but can't get any smart way of doing this except using indexOf() in java. Any better idea? Or improvement?


  • 0
    L

    An improvement is using the KMP algorithm


Log in to reply
 

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