28. Implement strStr() - jiejackyzhang/leetcode-note GitHub Wiki
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
String类题目。
思路为比较needle和haystack中长度为needle.length()的子串。
public class Solution {
public int strStr(String haystack, String needle) {
if(needle.length() == 0) return 0;
if(needle.length() > haystack.length()) return -1;
for(int i = 0; i <= haystack.length() - needle.length(); i++) {
int j = 0;
while(haystack.charAt(i+j) == needle.charAt(j)) {
j++;
if(j == needle.length()) return i;
}
}
return -1;
}
}
也可采用String.substring()实现
public class Solution {
public int strStr(String haystack, String needle) {
if(haystack == null || needle == null || haystack.length() < needle.length()) return -1;
if(needle.equals("")) return 0;
int len1 = haystack.length();
int len2 = needle.length();
for(int i = 0; i <= len1 - len2; i++) {
if(haystack.charAt(i) == needle.charAt(0)) {
if(haystack.substring(i, i+len2).equals(needle)) {
return i;
}
}
}
return -1;
}
}