Very easy solution using hash map


  • -1
    P
    public class Solution {
        public int strStr(String haystack, String needle) {
            if(needle.equals("")) return 0;
            HashMap<String, Integer> table=new HashMap<String, Integer>();
            int len=needle.length();
            for(int i=0; i<haystack.length()-len+1; i++) {
                String substr=haystack.substring(i, i+len);
                table.put(substr, i);
                if(table.containsKey(needle)) {
                    return table.get(needle);
                }
            }
            return -1;
        }
    }

  • 1
    L

    It's totally meaningless to put string and index into a map.

    table.put(substr, i); if(table.containsKey(needle)) {
    return table.get(needle);
    }

    These 3 line should be done by if(substr.equals(needle)) return i;


Log in to reply
 

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