一、題目原型:
給定一個(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。