My O(n) Solution


  • 1
    S

    public class Solution {
    public int strStr(String haystack, String needle) {
    if(haystack==null ||needle==null ||haystack.length()<needle.length())
    return -1;

        int start=0;
        for(int i=0,j=0;i<haystack.length()&&j<needle.length();){
            if(haystack.charAt(i)!=needle.charAt(j)){
                start=start+1;
                i=start;
                j=0;
            }else{
                i++;
                j++;
            }
            
        }
        if((haystack.length()-start)<needle.length())
        start=-1;
        return start;
    }
    

    }


Log in to reply
 

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