Leetcode学习笔记:#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.
实现:
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 j = l1 - l2;
for(int i = 0; i <= j; i++){
if((haystack.substring(i,i+l2).equals(needle)){
return i;
}
}
return -1;
}
思路:
遍历一次。只需要遍历减去needle长度的haystack的长度,如果包含则返回i,不包含反回-1;