zoukankan      html  css  js  c++  java
  • 28. 实现 strStr()

    给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的
    第一个位置 (从0开始);
    如果不存在,则返回  -1;
    当 needle 是空字符串时:应返回 0 。

    输入: haystack = "hello", needle = "ll"
    输出: 2

    输入: haystack = "aaaaa", needle = "bba"
    输出: -1



    思路:详见注释。
     1 class Solution(object):
     2     def strStr(self, haystack, needle):
     3         """
     4         :type haystack: str
     5         :type needle: str
     6         :rtype: int
     7         """
     8         # 若子串为空
     9         if needle == "":
    10             return 0
    11         # 若两串相同
    12         if len(haystack) == len(needle):
    13             if haystack == needle:
    14                 return 0
    15             else:
    16                 return -1
    17         # 获取两个串的长度
    18         size1 = len(haystack)
    19         size2 = len(needle)
    20         print("两个串的长度分别是:", size1, size2)
    21         for index in range(size1):
    22             ans = index
    23             j = 0
    24             while j < size2 and ans < size1 and haystack[ans] == needle[j]:
    25                 j += 1
    26                 ans += 1
    27             if j == size2:
    28                 return index
    29         return -1 if needle else 0
    30 
    31 if __name__ == '__main__':
    32     solution = Solution()
    33     print(solution.strStr("aaa", "a"))
    34     print(solution.strStr("hello", "lo"))
    35     print(solution.strStr("hello", "el"))
    
    
    
     
  • 相关阅读:
    使用header发送状态代码
    apache rewrite模块基础知识
    Deprecated: Function set_magic_quotes_runtime() is deprecated
    Xmind3.3强烈推荐
    windows 下安装svn服务
    Zend Studio 8
    mysql触发器
    程序员每天该做的事(转载)
    你真的了解.NET中的String吗?
    VS2005中Build顺序的设定
  • 原文地址:https://www.cnblogs.com/panweiwei/p/12681946.html
Copyright © 2011-2022 走看看