28. 實(shí)現(xiàn)strStr()

一、題目原型:

給定一個(gè) haystack 字符串和一個(gè) needle 字符串,在 haystack 字符串中找出 needle 字符串出現(xiàn)的第一個(gè)位置 (從0開(kāi)始)。如果不存在,則返回 -1。

二、示例剖析:

 輸入: haystack = "hello", needle = "ll"
 輸出: 2
 
 輸入: haystack = "aaaaa", needle = "bba"
 輸出: -1

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

三、解題思路:

1.方法簡(jiǎn)單,運(yùn)用swift語(yǔ)言特性

func strStr(_ haystack: String, _ needle: String) -> Int {
    if needle.count == 0 {
        return 0
    }
    let range = haystack.range(of: needle)
    return range?.lowerBound.encodedOffset ?? -1
}

2.將字符串變成數(shù)組,進(jìn)行遍歷。(借鑒top1的方案,其實(shí)也簡(jiǎn)單,就是看起來(lái)代碼貌似會(huì)比較多)

func strStr(_ haystack: String, _ needle: String) -> Int {
    let count1 = haystack.count
    let count2 = needle.count
    if count2 == 0 {
        return 0
    }
    
    if count1 < count2 {
        return -1
    }
    
    var haystackChars = haystack.cString(using: .utf8)!
    var needleChars = needle.cString(using: .utf8)!
    var i = 0
    var j = 0
    
    let maxi = count1 - count2
    let maxj = count2 - 1
    
    while i <= maxi && j <= maxj {
        var m = i
        while m <= count1 - 1 && j <= maxj {
            let mv = haystackChars[m]
            let jv = needleChars[j]
            if mv == jv {
                m += 1
                j += 1
                continue
            }
            j = 0
            i += 1
            break
        }
    }
    j = j - 1
    if j == maxj{
        return i
    }
    
    return -1
}

四、小結(jié)

1.耗時(shí)856毫秒,超過(guò)32.58%的提交記錄,總提交數(shù)74。
2.耗時(shí)12毫秒,超過(guò)100%的提交記錄,總提交數(shù)74

個(gè)人博客地址

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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