标签:
implement strStr()
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
brute force
don’t overlook this simple question. be careful on the details.
edgecase:
haystack == null? false
needle == null? false
needle isEmpty()?? 0
public int strStr(String haystack, String needle) { if(haystack == null || needle == null) return -1; if(needle.length() == 0) return 0; //haystack "aaa" //needle "a" for(int i = 0; i < haystack.length()-needle.length()+1; i++){ if(haystack.charAt(i) == needle.charAt(0)){ int j = 1; for(; j < needle.length(); j++){ if(haystack.charAt(i+j) != needle.charAt(j)){ break; } } if(j == needle.length()) return i; } } return -1; }
标签:
原文地址:http://www.cnblogs.com/momoco/p/4848141.html