当前位置:网站首页>leetcode3、實現 strStr()
leetcode3、實現 strStr()
2022-07-06 01:41:00 【東方不敗就是我】
實現 strStr() 函數。
給你兩個字符串 haystack 和 needle ,請你在 haystack 字符串中找出 needle 字符串出現的第一個比特置(下標從 0 開始)。如果不存在,則返回 -1 。
說明:
當 needle 是空字符串時,我們應當返回什麼值呢?這是一個在面試中很好的問題。
對於本題而言,當 needle 是空字符串時我們應當返回 0 。這與 C 語言的 strstr() 以及 Java 的 indexOf() 定義相符。
示例 1:
輸入:haystack = "hello", needle = "ll"
輸出:2
示例 2:
輸入:haystack = "aaaaa", needle = "bba"
輸出:-1
提示:
1 <= haystack.length, needle.length <= 104
haystack 和 needle 僅由小寫英文字符組成
個人解答
方法一:
def strStr(str1,str2):
return str1.find(str2)
str1="hello"
str2="ll"
print(strStr(str1,str2))
這個解答用了字符串內置的函數,太投機取巧。
方法二:
class Solution:
def strStr(self,str1,str2):
i=0
while(i<len(str1)):
if((str1[i:i+len(str2)])==str2):
return i
else:
i=i+1
else:
return -1
自己思路,采用切片方法。(是之前回文串時候的思路,由此可見,就算題做完,也一定要review,對以後做題有好處。)
官方解答
沒錯,我用的是暴力匹配,但KMP是什麼?
边栏推荐
- 037 PHP login, registration, message, personal Center Design
- NiO related knowledge (II)
- 02.Go语言开发环境配置
- Leetcode skimming questions_ Sum of squares
- [network attack and defense training exercises]
- Leetcode sum of two numbers
- 阿里测开面试题
- Loop structure of program (for loop)
- Basic operations of databases and tables ----- non empty constraints
- [the most complete in the whole network] |mysql explain full interpretation
猜你喜欢
ORA-00030
leetcode刷题_平方数之和
Basic process and testing idea of interface automation
c#网页打开winform exe
晶振是如何起振的?
插卡4G工业路由器充电桩智能柜专网视频监控4G转以太网转WiFi有线网速测试 软硬件定制
You are using pip version 21.1.1; however, version 22.0.3 is available. You should consider upgradin
Electrical data | IEEE118 (including wind and solar energy)
Huawei Hrbrid interface and VLAN division based on IP
National intangible cultural heritage inheritor HD Wang's shadow digital collection of "Four Beauties" made an amazing debut!
随机推荐
Unity VR solves the problem that the handle ray keeps flashing after touching the button of the UI
3D model format summary
正则表达式:示例(1)
[技术发展-28]:信息通信网大全、新的技术形态、信息通信行业高质量发展概览
电气数据|IEEE118(含风能太阳能)
[flask] obtain request information, redirect and error handling
【Flask】静态文件与模板渲染
Comments on flowable source code (XXXV) timer activation process definition processor, process instance migration job processor
ctf. Show PHP feature (89~110)
General operation method of spot Silver
[flask] response, session and message flashing
Maya hollowed out modeling
Leetcode 208. Implement trie (prefix tree)
3D视觉——4.手势识别(Gesture Recognition)入门——使用MediaPipe含单帧(Singel Frame)和实时视频(Real-Time Video)
Internship: unfamiliar annotations involved in the project code and their functions
[机缘参悟-39]:鬼谷子-第五飞箝篇 - 警示之二:赞美的六种类型,谨防享受赞美快感如同鱼儿享受诱饵。
Paddle框架:PaddleNLP概述【飛槳自然語言處理開發庫】
Threedposetracker project resolution
【全网最全】 |MySQL EXPLAIN 完全解读
ORA-00030