Java solution with two pointers


  • 0
    K
    class Solution {
        public int strStr(String haystack, String needle) {
            
            if(haystack.length() < needle.length()) return -1;
            if(haystack.length() == 0 || needle.length() == 0) return 0;
            
            if(haystack.equals(needle)) return 0;
            
            int start=0;
            int end=haystack.length() - 1;
            int patlen = needle.length() - 1;
            int patindex = 0;
            int foundindex = -1;
            
            while(start <= end){
                
                if(haystack.charAt(start) == needle.charAt(patindex)){                                              
                    if(patindex == patlen ){
                        foundindex = start - patlen ;
                        break;
                    }
                    else
                    patindex++;
                }
                else{
                    start = start - patindex; //eg:  "mississippi" "issip" (resetting start index)
                    patindex=0;                   
                }
                start++;
                
            }
            return foundindex;
            
        }
    }
    

Log in to reply
 

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