28.Implement strStr()(Easy)

Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
返回needle在haystack中第一次出現(xiàn)的位置的索引值,如果沒有找到,就返回-1

  就是尋常的字符串匹配搜索,應(yīng)該因為是簡單題,所以樸素的循環(huán)比較也能過,事實上應(yīng)該要用KMP算法的

My Solution

(Java) Version 1 Time: 7ms:

  這就是一個典型的樸素的兩重循環(huán)比較的算法,沒有什么好說的


public class Solution {
    public int strStr(String haystack, String needle) {
        if(haystack.length()==needle.length()){
            if(haystack.length()==0)return 0;
            else if(haystack.equals(needle))return 0;
            else return -1;
        }
        else if(needle.length()==0)return 0;
        char[] c1=haystack.toCharArray();
        char[] c2=needle.toCharArray();
        for(int i=0;i<c1.length-c2.length+1;i++){
            for(int j=0;j<c2.length;j++){
                //System.out.println(c2[j]+"__"+c1[j+i]);
                if(c2[j]!=c1[j+i])
                    break;
                else if(j==c2.length-1)
                    return i;
            }
        }
        return -1;
    }
}

(Java) Version 2 Time: 6ms (By Kexin_Li):

  講道理,我內(nèi)心的想法就是——這TMD也可以??不是很懂contains的使用范圍

public class Solution {
    public int strStr(String haystack, String needle) {
        return haystack.contains(needle) ? haystack.indexOf(needle) : -1;
    }
}

(Java) Version 3 Time: 6ms (By Domenickd3):

  這是用substring切割了字符串,然后做比較,事實上和兩個循環(huán)并無多大不同,只是第二個循環(huán)用了Java自己的方法,也許對比直接用for循環(huán)會有優(yōu)化

public class Solution {
    public int strStr(String haystack, String needle) {
        for (int i = 0; i < haystack.length() - needle.length() + 1; ++i) {
            if (haystack.substring(i, i + needle.length()).equals(needle)) {
                return i;
            }
        }
        return -1;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容