Java simple & easy to undestand solution


  • 0
    S
    public int strStr(String haystack, String needle) {
            if(needle.compareTo("") == 0) {
                return 0;
            }
        
            for(int i=0;i<=haystack.length()-needle.length();) {
                int j = 0;
                int start = i;
                while(j<needle.length() && needle.charAt(j) == haystack.charAt(i)) {
                    j++;
                    i++;
                }
                if(j==needle.length()){
                    return start;
                }
                i = start+1;
            }
            
            return -1;
            
        }

Log in to reply
 

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