Skip to content

Commit

Permalink
finish Problem 28
Browse files Browse the repository at this point in the history
  • Loading branch information
aQua authored and aQua committed Aug 1, 2017
1 parent c0ada66 commit 829b8fc
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 7 deletions.
4 changes: 3 additions & 1 deletion Algorithms/0028.implement-strstr/README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
# [28. Implement strStr()](https://leetcode.com/problems/implement-strstr/)

## 题目
Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

## 解题思路

依次对比查找

## 总结

Expand Down
11 changes: 11 additions & 0 deletions Algorithms/0028.implement-strstr/implement-strstr.go
Original file line number Diff line number Diff line change
@@ -1,2 +1,13 @@
package Problem0028

func strStr(haystack string, needle string) int {
hlen, nlen := len(haystack), len(needle)
// 当hlen等于nlen的时候,需要i == 0
for i := 0; i <= hlen-nlen; i++ {
if haystack[i:i+nlen] == needle {
return i
}
}

return -1
}
28 changes: 22 additions & 6 deletions Algorithms/0028.implement-strstr/implement-strstr_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package Problem0028

import (
"testing"
"fmt"
"testing"

"github.com/stretchr/testify/assert"
)
Expand All @@ -16,12 +16,13 @@ type question struct {
// one 代表第一个参数
type para struct {
one string
two string
}

// ans 是答案
// one 代表第一个答案
type ans struct {
one string
one int
}

func Test_Problem0028(t *testing.T) {
Expand All @@ -30,17 +31,32 @@ func Test_Problem0028(t *testing.T) {
qs := []question{

question{
para{""},
ans{""},
para{"", ""},
ans{0},
},


question{
para{"abcd", "bc"},
ans{1},
},

question{
para{"abcde", "c"},
ans{2},
},

question{
para{"abcde", "f"},
ans{-1},
},

// 如需多个测试,可以复制上方元素。
}

for _, q := range qs {
a, p := q.ans, q.para
fmt.Printf("~~%v~~\n", p)

ast.Equal(a.one, (p.one), "输入:%v", p)
ast.Equal(a.one, strStr(p.one, p.two), "输入:%v", p)
}
}

0 comments on commit 829b8fc

Please sign in to comment.