Implement strStr()
1 min readMar 19, 2019
Question: Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
You may view the full question here.
Approach 1:
//Approach 1:
//Runtime: 3ms
//Memory usage: 38.5MBclass Solution {
public int strStr(String haystack, String needle) {
if(needle==null || needle.length()==0){
return 0;
}
int size = haystack.length();
int needleSize = needle.length();
char lastChar = needle.charAt(needleSize-1);
for(int i = needleSize-1; i<size; i++){
if(lastChar==haystack.charAt(i)){
if(haystack.substring(i+1-needleSize,i+1).equals(needle)){
return i+1-needleSize;
}
}
}
return -1;
}
}
Find more posts here.
Cheers & Chao!