美文网首页
28. Implement strStr() 实现 strStr

28. Implement strStr() 实现 strStr

作者: sarto | 来源:发表于2022-03-26 12:29 被阅读0次

题目

对一个给定字符串 haystackneedle 如果 needle 是 haystack 的子串,返回 needle 在 haystack 中的位置。如果不存在,返回 -1。
边界:如果 needle 是一个空字符串,返回什么,返回 0。

解析

  1. 游标 i 指向 haystack 第一个元素,然后和 needle 比较
  2. 将 i 和 needle 逐字比较,如果相等, 返回 i
  3. 如果不等,移动 i。

伪代码

if needle.len == 0
    return 0
for i<haystack.len; i++
  for j<needle.len-1;j++
    if needle[j] != haystack[i+j]
        break
  if j == needle.len-1 && needle[j] == haystack[i+j]
    return i
  return -1

代码

func strStr(haystack string, needle string) int {
    for i:=0; i<len(haystack)-len(needle)+1; i++ {
        j:=0
        for ;j<len(needle);j++ {
            if needle[j] != haystack[i+j] {
                break
            }
        }
        if j == len(needle) {
            return i
        }
    }
    return -1
}

后记

  1. haystack 的循环终止条件应该是两个字符串之差
  2. 用 j 的返回位置来标识是否全部匹配完成

相关文章

网友评论

      本文标题:28. Implement strStr() 实现 strStr

      本文链接:https://www.haomeiwen.com/subject/mjtsjrtx.html