当前位置:网站首页>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是什么?
边栏推荐
- C web page open WinForm exe
- UE4 unreal engine, editor basic application, usage skills (IV)
- Reasonable and sensible
- 现货白银的一般操作方法
- Folio. Ink is a free, fast and easy-to-use image sharing tool
- Loop structure of program (for loop)
- Leetcode1961. Check whether the string is an array prefix
- NLP第四范式:Prompt概述【Pre-train,Prompt(提示),Predict】【刘鹏飞】
- selenium 等待方式
- 晶振是如何起振的?
猜你喜欢
MySQL learning notes 2
现货白银的一般操作方法
How does the crystal oscillator vibrate?
[flask] official tutorial -part3: blog blueprint, project installability
[ssrf-01] principle and utilization examples of server-side Request Forgery vulnerability
黄金价格走势k线图如何看?
Kubernetes stateless application expansion and contraction capacity
About error 2003 (HY000): can't connect to MySQL server on 'localhost' (10061)
一图看懂!为什么学校教了你Coding但还是不会的原因...
500 lines of code to understand the principle of mecached cache client driver
随机推荐
ClickOnce 不支持请求执行级别“requireAdministrator”
Crawler request module
Redis-Key的操作
Kubernetes stateless application expansion and contraction capacity
LeetCode 322. Change exchange (dynamic planning)
What is weak reference? What are the weak reference data types in ES6? What are weak references in JS?
干货!通过软硬件协同设计加速稀疏神经网络
A Cooperative Approach to Particle Swarm Optimization
Force buckle 1020 Number of enclaves
[flask] response, session and message flashing
Initialize MySQL database when docker container starts
Alibaba-Canal使用详解(排坑版)_MySQL与ES数据同步
[detailed] several ways to quickly realize object mapping
yii中console方法调用,yii console定时任务
2022年广西自治区中职组“网络空间安全”赛题及赛题解析(超详细)
Condition and AQS principle
Docker compose configures MySQL and realizes remote connection
Electrical data | IEEE118 (including wind and solar energy)
[le plus complet du réseau] | interprétation complète de MySQL explicite
Yii console method call, Yii console scheduled task