LC 实现 strStr()
swift 代码如下:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
print(strStr("hello", "ll"))
print(strStr("aaaaa", "bba"))
}
func strStr(_ haystack: String, _ needle: String) -> Int {
if needle.isEmpty {
return 0
}
let array1 = Array(haystack)
let array2 = Array(needle)
var i = 0
while (i + array2.count) <= array1.count {
let temp: Array = Array(array1[i...i + array2.count - 1])
if temp == array2 {
return i
}
i += 1
}
return -1
}
}
思路:
指针向右移,对比