Share my easy Java Solution(Morris-Pratt Algorithm)


  • 0
    A

    Compare needle with haystack char by char, if one char do not match, move to next char of haystack.

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

Log in to reply
 

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