美文网首页
字符串查找 (lintcode:strstr)

字符串查找 (lintcode:strstr)

作者: v1coder | 来源:发表于2018-01-03 22:45 被阅读0次

    字符串查找

    对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1。

    例如:
    如果 source = "source" 和 target = "target",返回 -1。
    如果 source = "abcdabcdefg" 和 target = "bcd",返回 1。

    我写的代码:

    # 题不难,但条件总是考虑不周全
    def strStr(source, target):
            # write your code here
        if target is None or source is None: # 没想到
            return -1
        if target == '': #当target为0时,source无论是什么字符串,都包含target
            return 0
        elif target in source:
            source_list = source.split(target)
            return len(source_list[0])
        else:
            return -1
    

    后来搜索了下,才知道有find()

    def strStr(self, source, target):
      if target is None or source is None:
        return -1
      else:
        return source.find(target)
    

    函数知道的少累死人呐。

    不过下面的代码跟上面的比,总耗时居然更多。


    lintcode 原题

    20180103

    相关文章

      网友评论

          本文标题:字符串查找 (lintcode:strstr)

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