28. Implement strStr()
2024-10-10 22:03:40
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
最新文章
- 备份了我的CSDN博客
- js倒计时显示
- sql语句获取今天、昨天、近7天、本周、上周、本月、上月、半年数据
- word to word
- SQL Server 查询处理中的各个阶段(SQL执行顺序)
- IT战略规划咨询
- $key 的用法
- 用WIN7系统IIS的提示:数据库连接出错,请检查Conn.asp文件中的数据库参数设置
- [转]安装openoffice,并且配置为windows服务
- ubuntu完美搭建git服务器【转】
- [转载]我读过最好的Epoll模型讲解
- 面试知识:操作系统、计算机网络、设计模式、Linux编程,数据结构总结
- poj3308Paratroopers(dinic)
- 兼容IE6/IE7/IE8/FireFox的css hack
- Ubuntu Builder —— 一个制作自己的发行版的工具
- Android 颜色配置表-颜色类
- DDD 应对具体业务场景,Domain Model 重新设计
- VS2010 自定义向导
- Blog Part I
- 【爬虫】在Xpath中使用正则
热门文章
- Oracle EBS 初始化用户密码(转)
- VM环境下,快速复制多个SQLServer实例,环境调整
- yii2得到的数据对象转化成数组
- Win10 驱动装不上,提示:Windows 无法验证此设备所需的驱动程序的数字签名。该值受安全引导策略保护,无法进行修改或删除。
- 轻松三步教你配置Oracle—windows环境
- MaxScale:实现MySQL读写分离与负载均衡的中间件利器
- go语言-helloworld
- 关于Android中ArrayMap/SparseArray比HashMap性能好的深入研究
- Windows平台Tomcat服务搭建
- 注释声明:TODO HACK XXX FIXME REVIEW