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

边栏推荐
- Kubernetes stateless application expansion and contraction capacity
- General operation method of spot Silver
- Win10 add file extension
- What is weak reference? What are the weak reference data types in ES6? What are weak references in JS?
- Internship: unfamiliar annotations involved in the project code and their functions
- DOM introduction
- 【详细】快速实现对象映射的几种方式
- Redis-字符串类型
- 2022年广西自治区中职组“网络空间安全”赛题及赛题解析(超详细)
- 网易智企逆势进场,游戏工业化有了新可能
猜你喜欢

How to upgrade kubernetes in place

02.Go语言开发环境配置

VMware Tools installation error: unable to automatically install vsock driver

C web page open WinForm exe

Alibaba canal usage details (pit draining version)_ MySQL and ES data synchronization

Force buckle 1020 Number of enclaves

基於DVWA的文件上傳漏洞測試

Kubernetes stateless application expansion and contraction capacity
![[Jiudu OJ 09] two points to find student information](/img/35/25aac51fa3e08558b1f6e2541762b6.jpg)
[Jiudu OJ 09] two points to find student information

Alibaba-Canal使用详解(排坑版)_MySQL与ES数据同步
随机推荐
leetcode刷题_平方数之和
Crawler request module
Leetcode sword finger offer 59 - ii Maximum value of queue
Format code_ What does formatting code mean
Reasonable and sensible
竞赛题 2022-6-26
dried food! Accelerating sparse neural network through hardware and software co design
A Cooperative Approach to Particle Swarm Optimization
Force buckle 9 palindromes
Leetcode1961. 检查字符串是否为数组前缀
Remember that a version of @nestjs/typeorm^8.1.4 cannot be obtained Env option problem
A glimpse of spir-v
[flask] static file and template rendering
MySQL learning notes 2
Une image! Pourquoi l'école t'a - t - elle appris à coder, mais pourquoi pas...
Redis守护进程无法停止解决方案
一图看懂!为什么学校教了你Coding但还是不会的原因...
【详细】快速实现对象映射的几种方式
ctf. Show PHP feature (89~110)
【网络攻防实训习题】