問題:函數
Implement strStr().指針
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.字符串
Example 1:string
Input: haystack = "hello", needle = "ll" Output: 2
Example 2:io
Input: haystack = "aaaaa", needle = "bba" Output: -1
解決:class
【注】strStr(String haystack, String needle):用於判斷字符串str2是不是str1的子串。若是是,則該函數返回str2在str1中首次出現的地址;不然,返回 -1。遍歷
① 使用兩個指針順序遍歷兩個字符串的每個元素便可。注意p1每次失敗後只能移向第一個字符的下一個位置,不然會漏掉不少組合。方法
public class Solution{//14ms
public int strStr(String haystack, String needle) {//子串是按順序排放的
if(needle.length() == 0) return 0;
int p1 = 0;
int p2 = 0;
int fir = 0;//記錄起始位置
int next =1;
int count = 0;//記錄匹配的個數
while(p1 < haystack.length()){
if(haystack.charAt(p1) == needle.charAt(p2)){
count ++;
p1 ++;
p2 ++;
}else{
count = 0;
p2 = 0;
p1 = next;
fir = p1;
next = fir + 1;
}
if(count == needle.length()) return fir;
}
return -1;
}
}next
② 最簡單的方法是直接調用String類的函數。while
public class Solution {//6ms
public int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
}
③ 第①種方法的進化版。也調用了String類的方法。
public class Solution {//6ms public int strStr(String haystack, String needle) { if(needle.equals(haystack) || needle.length() == 0) return 0;//字符串相等或者字串爲空 if(haystack.length() == 0 || haystack.length() < needle.length()) return -1; int len = needle.length(); for(int i = 0; i < haystack.length(); i++){ if(haystack.charAt(i) == needle.charAt(0)){ if(i + len > haystack.length()) break; if(needle.equals(haystack.substring(i, i + len))) return i; } } return -1; } }