28. Implement strStr()
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
思路:一种坏坏的解法
public class Solution {
public int strStr(String haystack, String needle) {
StringBuilder sb = new StringBuilder(haystack);
int pos = sb.indexOf(needle);
return pos;
}
}
另一种:
public class Solution {
public int strStr1(String haystack, String needle) {
return haystack.indexOf(needle);
}
public int strStr(String haystack, String needle) {
if (haystack == null || needle == null) {
return -1;
}
int l1 = haystack.length();
int l2 = needle.length();
for (int i = 0; i< l1-l2+1; i++){
int count = 0;
while (count < l2 && haystack.charAt (i+count) == needle.charAt(count))
count++;
if (count == l2)
return i;
}
return -1;
}
}