2 pointer solution Java


  • 0
    A
    public class Solution {
        public int strStr(String haystack, String needle) {
            
            if (haystack == null || needle == null ) { return -1;}
            
            if (needle.isEmpty()) { return 0;}
            
            if (haystack.isEmpty() || haystack.length()<needle.length()) { return -1;}
            
            
            int i=0;
            
            while (i<=(haystack.length()-needle.length())) {
                int hCurr, nCurr;
                for (hCurr=i, nCurr=0; nCurr < needle.length(); hCurr++, nCurr++) {
                    
                    if (haystack.charAt(hCurr) != needle.charAt(nCurr)) {
                        break;
                    }
                }
                
                if (nCurr == needle.length()) { return i;}
                i++;
            }
            return -1;
        }
    }
    

Log in to reply
 

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