Very easy 7 line Java solution


  • -1
    S
    public int strStr(String haystack, String needle) 
        {
            // Condition 1- If needle is empty, match is found
            if(needle.length() == 0) return 0;
            
            int m = haystack.length();
            int n = needle.length();
            
            for(int i=0; i<= (m-n); i++)
            {
                String trial = haystack.substring(i, i+n);
                if(trial.equals(needle)) return i;
            }
            
            return -1;
            
        }

Log in to reply
 

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