Java 12ms Solution


  • 0
    Y
    public class Solution {
        public int strStr(String haystack, String needle) {
            if(needle.length() == 0 && (haystack.length() == 0 || haystack.length() != 0))
                return 0;
            int[] map = new int[26];
            for(int i=0; i<needle.length(); i++)
                map[needle.charAt(i) - 'a']++;
            for(int i=0; i<haystack.length(); i++){
                if(haystack.length() - i < needle.length())
                    return -1;
                if(map[haystack.charAt(i) - 'a'] > 0){
                    int index = i;
                    for(int j=0; j<needle.length(); j++){
                        if(haystack.charAt(index) == needle.charAt(j))
                            index++;
                        else{
                            break;
                        }
                    }
                    if(index - i == needle.length())
                        return i;
                    if(map[haystack.charAt(index) - 'a'] == 0)
                        i = index;
                }
            }
            return -1;
        }
    }

Log in to reply
 

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