Implement strStr().Return the index of the first occurrence of needle in haystack, or -1if needle isnot part of haystack.Example 1:Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:Input: haystack = "aaaaa", needle = "bba"
Output: -1
Clarification:What should we returnwhen needle is an empty string? This is a great question to ask during an interview.For the purpose of this problem, we will return0when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().
代码
class Solution {publicintstrStr(String haystack, String needle) {if(haystack==null||needle==null)return -1;if((needle.length()==0&&haystack.length()==0)||needle.length()==0)return0;int hlen = haystack.length();int nlen = needle.length();int i=0,j=0,k=0;while(hlen!=i&&nlen!=j&&hlen>=i&&nlen>=j){char h = haystack.charAt(i);char n = needle.charAt(j);if(h==n){i++;j++;}else{k++;i=k;j=0;}}if(nlen!=j)return -1;elsereturn i-j;}
}