LeetCode小白菜笔记[10]:Implement strStr()
来源:互联网 发布:理查德杰弗森生涯数据 编辑:程序博客网 时间:2024/06/10 03:04
LeetCode小白菜笔记[10]:Implement strStr()
28. Implement strStr() [Easy]
题目:Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"Output: -1
简言之,就是把后一个子串(needle)从前一个字符串(haystack)中提取出来,返回其第一次出现的位置,若不存在则返回 -1 。
代码比较简单,不过特殊情况比较坑。。。按照题目的意思,如果 needle 是空的,则返回 0 ,即认为在第一个位置找到了。改了好几次才通过。代码如下:
class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ if not needle: return 0 if len(haystack) < len(needle): return -1 if len(haystack) == len(needle): return int(haystack == needle) - 1 for idx in range(len(haystack) - len(needle) + 1): if haystack[idx:idx+len(needle)] == needle: return idx return -1
结果如下:
discuss里面的代码更简洁:
class Solution(object):def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ for i in range(len(haystack) - len(needle)+1): if haystack[i:i+len(needle)] == needle: return i return -1
有些特殊情况的处理可以纳入一般情况。如 len(needle)=0 的情况,haystack[ i : i ] = ”,因此返回0,符合题意,而且len(needle)比len(haystack)大的情况,由于haystack[ i : i + len(needle) ]如果后面的停止位置超出范围,则会一直取到haystack最末元素。因此永远不会相等,故最后 return - 1 。
总结:
通过设计算法将特殊情况纳入到普通情况来判断可以使得代码更简洁。
注意range和 [ i : j ] 的包含前项不包含后项的性质。
THE END
阅读全文
0 0
- LeetCode小白菜笔记[10]:Implement strStr()
- leetcode笔记:Implement strStr()
- LeetCode笔记:28. Implement strStr()
- 小白笔记-----------------------leetcode(28. Implement strStr())
- LeetCode: Implement strStr()
- [Leetcode] Implement strstr()
- Leetcode: Implement strStr
- [Leetcode] Implement strStr()
- LeetCode Implement strStr()
- 【leetcode】Implement strStr()
- [LeetCode]Implement strStr()
- [LeetCode] Implement strStr()
- [LeetCode] Implement strStr()
- LeetCode-Implement strStr()
- LeetCode: Implement strStr()
- LeetCode - Implement strStr()
- LeetCode: Implement strStr()
- 【leetcode】Implement strStr()
- 网秦发布2017年第一季度、第二季度及第三季度财报
- SpringMVC+Spring+Mybatis+Oracle 实现HR管理(CRUD)一数据库设计
- Linux Journal (Linux学报) 宣布停刊
- 漫画:PHP女程序员自救的技巧
- 世界上的程序员只分为俩种
- LeetCode小白菜笔记[10]:Implement strStr()
- 考题篇(5.4) NSE4 17. 入侵防御 ❀ 飞塔 (Fortinet) 网络安全专家
- Python第二课 字符串(1)
- 纪念写挂的T4--Day2017.12.14
- centos6.8源码安装php7.0
- 终于成功配置numba cuda
- 两个让你效率倍增的linux小命令
- 一个控制电脑关机的有趣程序
- 红茶一杯话Binder 四(传输机制篇_中)