28. 实现strStr()
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = "hello", needle = "ll" 输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba" 输出: -1
说明:
当 needle
是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle
是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
代码如下: 通过48ms
class Solution: def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ h = len(haystack) n = len(needle) for i in range(0, (h - n +1)): if haystack[i: i+n] == needle: return i return -1
14. 最长公共前缀
扫描二维码关注公众号,回复:
1544352 查看本文章
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
示例 1:
输入: ["flower","flow","flight"] 输出: "fl"
示例 2:
输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀。
说明:
所有输入只包含小写字母 a-z
。
代码如下: 耗时48ms,通过
class Solution: def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ #### python3 中封装了os.path.commonprefix(strs),基本和这个题的解法是一样的 if len(strs) == 0: return "" s1 = min(strs) s2 = max(strs) for i, char in enumerate(s1): if char != s2[i]: return s1[:i] return s1互相学习,互相指教