Description:
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Solution:
Only one needle need to be checked. Or else we need to use an Aho-Corasick automation. An equal function is enough here.
public class Solution {
public int strStr(String haystack, String needle) {
if (needle.equals(""))
return 0;
int len = needle.length();
for (int i = 0; i < haystack.length() - len + 1; i++) {
if (haystack.subSequence(i, i + len ).equals(needle))
return i;
}
return -1;
}
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.strStr("a", "a"));
}
}