Skip to content

Commit

Permalink
feat: Implement strStr()
Browse files Browse the repository at this point in the history
  • Loading branch information
leverz committed Mar 27, 2020
1 parent 8107470 commit 09c2824
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
|297|[二叉树的序列化与反序列化](https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/) | [Golang](./content/blog/algorithm/297.md)|
|99|[恢复二叉搜索树](https://leetcode-cn.com/problems/recover-binary-search-tree/)| [Golang](./content/blog/algorithm/99.md)|
|35|[搜索插入位置](https://leetcode-cn.com/problems/search-insert-position/)| [Golang](./content/blog/algorithm/35.md)|
|28|[实现 strStr()](https://leetcode-cn.com/problems/implement-strstr/)| [Golang](./content/blog/algorithm/28.md)|
|27|[移除元素](https://leetcode-cn.com/problems/remove-element/)| [Golang](./content/blog/algorithm/27.md)|
|26|[删除排序数组中的重复项](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/)| [Golang](./content/blog/algorithm/26.md)|
|25|[K 个一组翻转链表](https://leetcode-cn.com/problems/reverse-nodes-in-k-group/)| [Golang](./content/blog/algorithm/25.md)|
Expand Down
36 changes: 36 additions & 0 deletions content/blog/algorithm/28.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
---
title: 28. 实现 strStr()
date: '2020-03-27T22:35:00.000Z'
---

[https://leetcode-cn.com/problems/implement-strstr/](https://leetcode-cn.com/problems/implement-strstr/)

# 解:

func strStr(haystack string, needle string) int {
if len(haystack) < len(needle) {
return -1
}
var i, j int
for i < len(haystack) {
if j >= len(needle) {
return i - j
}
if haystack[i] == needle[j] {
j++
i++
} else {
i = i - j + 1
j = 0
}
}

if j == len(needle) {
return i - j
}
return -1
}

题目比较简单,就是边界条件不好处理。用 i 和 j 分别控制 haystack 和 needle 的遍历进度,并挨个比较。相等的话两者继续向后比较,不相等,就重置 j,并将 i 移动到本轮的开始位置的下一元素,重新与 needle 进行比较。

匹配成功的条件有两种,一种是 needle 已经遍历完成,haystack 还没遍历完成,此时直接返回 i - j 即为开始位置的索引。一种是 needle 和 haystack 同时遍历完成,同样也返回 i - j 即可。只要遍历完成并且 j 的大小与 needle 长度不同,就可以认为没有匹配成功,返回 -1。

0 comments on commit 09c2824

Please sign in to comment.