题目描述
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2: Input: haystack = "aaaaa", needle = "bba"
Output: -1
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().
解题思路
这个题目主要是实现字符串的查找, 首先进行一些判断, 然后遍历从 index=0 开始获取长度等于 needle 长度的子串, 如果这个子串等于 needle 就返回 index.
时间复杂度: O(n)
示例代码
func strStr(_ haystack: String, _ needle: String) -> Int {
if (needle.count == 0) {
return 0
}
if (haystack.count - needle.count < 0) {
return -1
}
let gapLength = haystack.count - needle.count
for i in 0...gapLength {
let tempStr = (haystack as NSString).substring(with: NSRange(location: i, length: needle.count))
if tempStr == needle {
return i
}
}
return -1
}