JAVA solution


  • 0
    S

    class Solution {
    public int strStr(String haystack, String needle) {

        if (needle.equals("")&& haystack.equals("")){
            return 0;
        }
        if (needle.equals("")){
            return 0;
        }
    
        int match = 0 ;
        int start = -1;
        for (int i=0;i< haystack.length() ;i++){
            if (haystack.charAt(i) == needle.charAt(match++)){
                start = start == -1? i:start;
                if (match == needle.length()){
                    return start;
                }
            }else {
                if (start!=-1){
                    i = start;
                }
                start = -1;
                match = 0;
    
            }
        }
        if (match == needle.length()){
            return start;
        }else {
            return -1;
        }
    }
    

    }


Log in to reply
 

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