Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

1

 class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
return haystack.find(needle)

2 brute force

class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
result = -1
l_needle = len(needle)
l_haystack = len(haystack)
if l_needle == 0 and l_haystack == 0:
return 0
if l_haystack == 0 and l_needle!=0:
return result
if l_needle == 0 :
return 0
for index in range(l_haystack):
if l_haystack - index >= l_needle and needle == haystack[index:index+l_needle]:
result = index
break
return result

3 hash 有待改进

class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
result = -1
l_needle = len(needle)
l_haystack = len(haystack)
if l_needle == 0 and l_haystack == 0:
return 0
if l_haystack == 0 and l_needle!=0:
return result
if l_needle == 0 :
return 0
if l_needle>l_haystack:
return result
hash_needle=hash(needle)
list_haystack=[]
for index in range(l_haystack):
if index<=(l_haystack-l_needle):
list_haystack.append(hash(haystack[index:index+l_needle]))
result=list_haystack.index(hash_needle) if hash_needle in list_haystack else -1
return result

最新文章

  1. 备份了我的CSDN博客
  2. js倒计时显示
  3. sql语句获取今天、昨天、近7天、本周、上周、本月、上月、半年数据
  4. word to word
  5. SQL Server 查询处理中的各个阶段(SQL执行顺序)
  6. IT战略规划咨询
  7. $key 的用法
  8. 用WIN7系统IIS的提示:数据库连接出错,请检查Conn.asp文件中的数据库参数设置
  9. [转]安装openoffice,并且配置为windows服务
  10. ubuntu完美搭建git服务器【转】
  11. [转载]我读过最好的Epoll模型讲解
  12. 面试知识:操作系统、计算机网络、设计模式、Linux编程,数据结构总结
  13. poj3308Paratroopers(dinic)
  14. 兼容IE6/IE7/IE8/FireFox的css hack
  15. Ubuntu Builder —— 一个制作自己的发行版的工具
  16. Android 颜色配置表-颜色类
  17. DDD 应对具体业务场景,Domain Model 重新设计
  18. VS2010 自定义向导
  19. Blog Part I
  20. 【爬虫】在Xpath中使用正则

热门文章

  1. Oracle EBS 初始化用户密码(转)
  2. VM环境下,快速复制多个SQLServer实例,环境调整
  3. yii2得到的数据对象转化成数组
  4. Win10 驱动装不上,提示:Windows 无法验证此设备所需的驱动程序的数字签名。该值受安全引导策略保护,无法进行修改或删除。
  5. 轻松三步教你配置Oracle—windows环境
  6. MaxScale:实现MySQL读写分离与负载均衡的中间件利器
  7. go语言-helloworld
  8. 关于Android中ArrayMap/SparseArray比HashMap性能好的深入研究
  9. Windows平台Tomcat服务搭建
  10. 注释声明:TODO HACK XXX FIXME REVIEW