這道題我第一反應就是indexOf函數,我使用了,直接經過,6ms。算法
算法我也是看了看答案,腦殼昏沉沉,沒動腦想,不過理解了函數
------------------------------------------------------------------------------string
class Solution {
public int strStr(String haystack, String needle) {
if(needle.equals("")) return 0;
if(haystack.length() < needle.length()) return -1;
int tag = haystack.length() - needle.length();
for(int i = 0;i <= tag;i++){
if(haystack.substring(i,i + needle.length()).equals(needle)){
return i;
}
}
return -1;io
1.先判斷子串是否爲空,空的話返回0;class
2.當子串大於haystack,返回負一變量
3.主要是tag變量,用於防止下標越界遍歷
4.index從i開始遍歷,每次遍歷長度爲needle的長度,i++的比較每一位return
5.當i=tag時,證實比較到最後面了,i+needle.length=haystack.lengthindex