当前位置:网站首页>leetcode3、实现 strStr()
leetcode3、实现 strStr()
2022-07-06 01:36: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是什么?
边栏推荐
- A picture to understand! Why did the school teach you coding but still not
- [solved] how to generate a beautiful static document description page
- 2022年PMP项目管理考试敏捷知识点(8)
- PHP error what is an error?
- Netease smart enterprises enter the market against the trend, and there is a new possibility for game industrialization
- NLP fourth paradigm: overview of prompt [pre train, prompt, predict] [Liu Pengfei]
- 干货!通过软硬件协同设计加速稀疏神经网络
- 2022 Guangxi Autonomous Region secondary vocational group "Cyberspace Security" competition and its analysis (super detailed)
- Leetcode1961. 检查字符串是否为数组前缀
- Leetcode skimming questions_ Invert vowels in a string
猜你喜欢
MySQL learning notes 2
c#网页打开winform exe
Hcip---ipv6 experiment
Alibaba canal usage details (pit draining version)_ MySQL and ES data synchronization
XSS learning XSS lab problem solution
C web page open WinForm exe
037 PHP login, registration, message, personal Center Design
ORA-00030
MATLB | real time opportunity constrained decision making and its application in power system
How to see the K-line chart of gold price trend?
随机推荐
How to get the PHP version- How to get the PHP Version?
【Flask】官方教程(Tutorial)-part1:项目布局、应用程序设置、定义和访问数据库
selenium 等待方式
01.Go语言介绍
leetcode刷题_反转字符串中的元音字母
yii中console方法调用,yii console定时任务
Reasonable and sensible
Leetcode1961. Check whether the string is an array prefix
Alibaba canal usage details (pit draining version)_ MySQL and ES data synchronization
500 lines of code to understand the principle of mecached cache client driver
Leetcode 208. 实现 Trie (前缀树)
竞赛题 2022-6-26
[flask] response, session and message flashing
How to upgrade kubernetes in place
National intangible cultural heritage inheritor HD Wang's shadow digital collection of "Four Beauties" made an amazing debut!
[technology development -28]: overview of information and communication network, new technology forms, high-quality development of information and communication industry
干货!通过软硬件协同设计加速稀疏神经网络
电气数据|IEEE118(含风能太阳能)
Kubernetes stateless application expansion and contraction capacity
Force buckle 9 palindromes