Two pointer Java Solution


  • 0
    R

    The key here is to check the length of haystack left to compare with the needle.Rest is pretty simple and anyone can guess on first thought.

    public class Solution {
        public int strStr(String haystack, String needle) {
            int i=0,j=0;            
            if(haystack==null || needle == null)
                return -1;        
            if(needle.length()>haystack.length())
                return -1;        
            while(i<haystack.length()){
                j=0;
                if((haystack.length()-1 - i) < needle.length()-1)
                    return -1;
                while(j<needle.length()){
                    if(haystack.charAt(i+j) != needle.charAt(j))
                        break;
                    j++;
                }
                if(j==needle.length())
                    break;
                i++;
            }        
            if(j!=needle.length())
                return -1;        
            return i;        
        }
    }
    

Log in to reply
 

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