本文是在學習中的總結,歡迎轉載但請注明出處:http://blog.csdn.net/pistolove/article/details/41452047
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char
*
or String
, please click the reload button to
reset your code definition.
這道題很簡單,這裡就不啰嗦了。下面給出我自己的解題算法和網站上給出公認的性能比較好的算法,顯然,我寫的算法還不夠好,僅僅作為參考,希望對大家有所幫助。
本人的解題代碼如下:
public int strStr(String hack, String need) { int needlen = need.length(); int hacklen = hack.length(); if (needlen == 0) return 0; if (needlen == 0 && hacklen == 0 || needlen > hacklen) return -1; for (int i = 0; i < hacklen; i++) { int y = needlen; int x = i; if (y <= hacklen) { y = y + i; if (y > hacklen) return -1; String compare = hack.substring(x, y); if (need.equals(compare)) { return x; } } } return -1; }
網站上公認比較好的解題代碼如下:
public int strStr(String haystack, String needle) { for (int i = 0;; i++) { for (int j = 0;; j++) { if (j == needle.length()) return i; if (i + j == haystack.length()) return -1; if (needle.charAt(j) != haystack.charAt(i + j)) break; } } }