当前位置:网站首页>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是什麼?
边栏推荐
- 【Flask】官方教程(Tutorial)-part2:蓝图-视图、模板、静态文件
- 剑指 Offer 38. 字符串的排列
- Docker compose configures MySQL and realizes remote connection
- Redis守护进程无法停止解决方案
- 【已解决】如何生成漂亮的静态文档说明页
- Une image! Pourquoi l'école t'a - t - elle appris à coder, mais pourquoi pas...
- Selenium element positioning (2)
- module ‘tensorflow. contrib. data‘ has no attribute ‘dataset
- leetcode刷题_反转字符串中的元音字母
- [flask] official tutorial -part2: Blueprint - view, template, static file
猜你喜欢
037 PHP login, registration, message, personal Center Design
Basic operations of databases and tables ----- primary key constraints
Leetcode3. Implement strstr()
1. Introduction to basic functions of power query
Force buckle 1020 Number of enclaves
MUX VLAN configuration
Leetcode sum of two numbers
How does the crystal oscillator vibrate?
NumPy 数组索引 切片
Docker compose configures MySQL and realizes remote connection
随机推荐
MATLB | real time opportunity constrained decision making and its application in power system
Leetcode sum of two numbers
Leetcode skimming questions_ Sum of squares
[detailed] several ways to quickly realize object mapping
Electrical data | IEEE118 (including wind and solar energy)
02.Go语言开发环境配置
Docker compose配置MySQL并实现远程连接
Format code_ What does formatting code mean
一圖看懂!為什麼學校教了你Coding但還是不會的原因...
Paddle framework: paddlenlp overview [propeller natural language processing development library]
Redis-列表
Dynamics 365 开发协作最佳实践思考
Card 4G industrial router charging pile intelligent cabinet private network video monitoring 4G to Ethernet to WiFi wired network speed test software and hardware customization
Basic operations of databases and tables ----- non empty constraints
Flutter Doctor:Xcode 安装不完整
Leetcode 208. Implement trie (prefix tree)
Accelerating spark data access with alluxio in kubernetes
2022年广西自治区中职组“网络空间安全”赛题及赛题解析(超详细)
Cookie concept, basic use, principle, details and Chinese transmission
Basic operations of databases and tables ----- primary key constraints