LeetCode(28. 實現(xiàn)strStr())

算法描述 :
實現(xiàn)strStr()函數(shù)。
給定一個 haystack 字符串和一個 needle 字符串,在 haystack 字符串中找出 needle 字符串出現(xiàn)的第一個位置 (從0開始)。如果不存在,則返回  -1。
示例 1:
輸入: haystack = "hello", needle = "ll"
輸出: 2

示例 2:
輸入: haystack = "aaaaa", needle = "bba"
輸出: -1

說明:
當(dāng) needle 是空字符串時,我們應(yīng)當(dāng)返回什么值呢?這是一個在面試中很好的問題。
對于本題而言,當(dāng) `needle` 是空字符串時我們應(yīng)當(dāng)返回 0 。這與C語言的 strstr()以及 Java的indexOf() 定義相符。

算法實現(xiàn) :

Java實現(xiàn) :

class Solution {
    public int strStr(String haystack, String needle) {
        if ("".equals(needle)) {
            return 0;
        }

        for (int i = 0; i < haystack.length(); i++) {
            if (haystack.charAt(i) != needle.charAt(0)) {  // haystack逐個字符與needle第一個字符比較
                continue;
            }

            // 從第一個相同字符開始向后掃描比較
            for (int j = 0; j < needle.length(); j++) {
                if (i + j < haystack.length()) {
                    if (haystack.charAt(i + j) != needle.charAt(j)) {  // 如某個字符不相等,則i+1重新來過
                        break;
                    }
                } else {
                    return -1;
                }

                if (j == needle.length() - 1) {  // 比較到needle最后一個字符, 返回haystack的索引
                    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)容