版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/huanglinxiao/article/details/91528192
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1
解法:
func strStr(_ haystack: String, _ needle: String) -> Int {
guard !needle.isEmpty else {
return 0
}
guard needle.count <= haystack.count else {
return -1
}
//1.拿到匹配的字符串needle
//2.在特定的字符串haystack中遍历查找
if haystack.contains(needle) {
let hays: NSString = haystack as NSString
let index:Int = hays.range(of: needle).location
return index
}else{
return -1
}
}