1. Description
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
2. Example
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
3. Code
import java.util.HashMap;
import java.util.Map;
public class LeetCode0028 {
public int strStr(String haystack, String needle)
{
if (haystack == null || needle == null || haystack.length() < needle.length()) {
return -1;
}
if (needle.length() == 0) {
return 0;
}
Map<Character, Integer> map = getShift(needle);
int maxLength = haystack.length() - needle.length();
for (int i = 0; i <= maxLength;) {
int j = 0;
for (; j < needle.length(); j++) {
if (haystack.charAt(i + j) != needle.charAt(j)) {
break;
}
}
if (j == needle.length()) {
return i;
}
i += needle.length();
if (i < haystack.length()) {
i -= map.getOrDefault(haystack.charAt(i), -1);
}
}
return -1;
}
private Map<Character, Integer> getShift(String needle)
{
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < needle.length(); i++) {
map.put(needle.charAt(i), i);
}
return map;
}
public static void main(String[] args)
{
LeetCode0028 leetcode = new LeetCode0028();
System.out.println(leetcode.strStr("hello", "ll"));
}
}
Comments | NOTHING