力扣 初级算法 全套力扣精解

初级算法-字符串-实现 strStr()

2021-08-22  本文已影响0人  coenen
实现 strStr() 函数。

给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。

说明:

当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。

对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。

摘一个示例做个说明.
示例 1:
输入:haystack = "hello", needle = "ll"
输出:2
条件分析:
  1. 两个字符串操作 -> haystack 涵盖字符串 needle
  2. 不存在则返回-1 -> 是否包含未知
  3. needle为空串时返回0
解决思路1:
  1. 根据分析1,先判断字符串是否相同,相同则肯定是符合条件
  2. 根据分析2,如果needle的字符串长度比较长,则肯定是不符合
  3. 根据分析3,如果needle为空串,直接返回即可.
先判断字符串是否相同或者needle为空串,如果是则返回0.如果不是,则判断needle是否是最长串.如果是则返回-1.则其余情况是haystack长度大于等于needle长度.则通过不断的截取haystack串,循环判断haystack是否以needle开头,以实现目的.如果存在则返回索引i即可.
func strStr(_ haystack: String, _ needle: String) -> Int {
    if haystack == needle || 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
}

测试用例:

包含 let haystack = "hello", needle = "ll"
不包含 let haystack = "hello", needle = "bll"
needle 空 let haystack = "hello", needle = ""

考察要点:

上一篇下一篇

猜你喜欢

热点阅读