28. Implement strStr()
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
1 2 3
| Input: haystack = "hello", needle = "ll" Output: 2
|
Example 2:
1 2 3
| Input: haystack = "aaaaa", needle = "bba" Output: -1
|
第一反应就是建立一个hashMap<String, Integer> 来存储substring和对应的index。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public int strStr(String haystack, String needle) { if(needle.length() == 0){ return 0; } int window = needle.length(); HashMap<String, Integer> m = new HashMap<String, Integer>(); for (int i=0;i<=haystack.length()-window; i++){ String substring = haystack.substring(i,i+window); m.put(substring, i); if(m.containsKey(needle)){ return m.get(needle); } } return -1; } }
|
but,在discuss区看到:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class Solution { public int strStr(String haystack, String needle) { int l1 = haystack.length(), l2 = needle.length(); if (l1 < l2) { return -1; } else if (l2 == 0) { return 0; } int threshold = l1 - l2; for (int i = 0; i <= threshold; ++i) { if (haystack.substring(i,i+l2).equals(needle)) { return i; } } return -1; } }
|