当前位置:网站首页>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是什麼?

边栏推荐
- UE4 unreal engine, editor basic application, usage skills (IV)
- SPIR-V初窥
- How to get the PHP version- How to get the PHP Version?
- [flask] official tutorial -part2: Blueprint - view, template, static file
- SPIR-V初窺
- Crawler request module
- c#网页打开winform exe
- Bidding promotion process
- CocoaPods could not find compatible versions for pod 'Firebase/CoreOnly'
- Dynamics 365 开发协作最佳实践思考
猜你喜欢

Alibaba-Canal使用详解(排坑版)_MySQL与ES数据同步

037 PHP login, registration, message, personal Center Design

Accelerating spark data access with alluxio in kubernetes

leetcode-两数之和

MATLB|实时机会约束决策及其在电力系统中的应用

Une image! Pourquoi l'école t'a - t - elle appris à coder, mais pourquoi pas...

How does the crystal oscillator vibrate?
Folio. Ink is a free, fast and easy-to-use image sharing tool

Initialize MySQL database when docker container starts
Folio.ink 免费、快速、易用的图片分享工具
随机推荐
yii中console方法调用,yii console定时任务
【Flask】官方教程(Tutorial)-part1:项目布局、应用程序设置、定义和访问数据库
module ‘tensorflow. contrib. data‘ has no attribute ‘dataset
Reasonable and sensible
Mathematical modeling learning from scratch (2): Tools
3D model format summary
竞价推广流程
【网络攻防实训习题】
Leetcode sum of two numbers
A Cooperative Approach to Particle Swarm Optimization
插卡4G工业路由器充电桩智能柜专网视频监控4G转以太网转WiFi有线网速测试 软硬件定制
[flask] static file and template rendering
[understanding of opportunity-39]: Guiguzi - Chapter 5 flying clamp - warning 2: there are six types of praise. Be careful to enjoy praise as fish enjoy bait.
阿裏測開面試題
Shutter doctor: Xcode installation is incomplete
MUX VLAN configuration
Crawler request module
MATLB|实时机会约束决策及其在电力系统中的应用
C web page open WinForm exe
General operation method of spot Silver