LeetCode Swift解题记录(28)实现 strStr()
题干解析
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置
(从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = “hello”, needle = “ll” 输出: 2
示例 2:
输入: haystack = “aaaaa”, needle = “bba” 输出: -1
个人解题:
class Solution {
func strStr(_ haystack: String, _ needle: String) -> Int {
if (needle.count == 0){
return 0
}
var range:Range? = haystack.range(of:needle)
var location:Int = 0
if (range != nil){
location = haystack.distance(from:haystack.startIndex,to:range!.lowerBound)
return location
}else{
return -1
}
}
}
思路心得:
调试没问题,提交提示超时
推荐解法:
class Solution {
func strStr(_ haystack: String, _ needle: String) -> Int {
if haystack == needle{
return 0
}
if haystack.count < needle.count{
return -1
}
var a:String=haystack
for i in 0...(a.count-needle.count){
if a.hasPrefix(needle){
return i
}
a.remove(at:a.startIndex)
}
return -1
}
}
推荐评价:
遍历删除,如果有当前字符串的前缀,则返回当前index,否则返回-1