当前位置:网站首页>String -- 28. Implement strstr()
String -- 28. Implement strstr()
2022-07-24 13:54:00 【Xiao Zhao, who is working hard for millions of annual salary】
1 Title Description
- Realization strStr()
Realization strStr() function .
Here are two strings haystack and needle , Please come in haystack Find in string needle The first place the string appears ( Subscript from 0 Start ). If it doesn't exist , Then return to -1 .
explain :
When needle When it's an empty string , What value should we return ? This is a good question in an interview .
For this question , When needle When it's an empty string, we should return 0 . This is related to C Linguistic strstr() as well as Java Of indexOf() The definition matches .
2 Title Example
Example 1:
Input :haystack = “hello”, needle = “ll”
Output :2
Example 2:
Input :haystack = “aaaaa”, needle = “bba”
Output :-1
3 Topic tips
1 <= haystack.length, needle.length <= 104
haystack and needle It only consists of lowercase English characters
4 Ideas
This problem is the classic string single-mode matching model , Therefore, it can be solved by string matching algorithm , Common string matching algorithms include violent matching 、Knuth-Morris-Pratt Algorithm 、Boyer-Moore Algorithm 、Sunday Algorithm etc. , This article will explain Knuth-Morris-Pratt Algorithm .
Because the hash method may have the same hash values but different strings , and strStr Function requires that the matching result must be correct , Therefore, this article does not introduce the hash method , Interested readers can learn about the implementation of rolling hash by themselves ( Such as Rabin-Karp Algorithm ).
Method 1 : Violence matching ideas and algorithms
We can make the string needle And string haystack All the lengths of are m All substrings of match once .
To reduce unnecessary matching , Every time we fail to match, we immediately stop the matching of the current substring , Continue matching for the next substring . If the current substring matches successfully , We can return the starting position of the current substring . If all substrings fail to match , Then return to —1.
Complexity analysis
Time complexity :o(n x m), among n Is string hagystack The length of ,m Is string needle The length of . In the worst case, we need to put the string needle And string haystack All the lengths of are m All substrings of match once .
Spatial complexity :O(1). We just need a constant space to hold a few variables .
Method 2 :KMP
No introduction , Too long , You can search for it yourself
5 My answer
Method 1 : violence
class Solution {
public int strStr(String haystack, String needle) {
int n = haystack.length(), m = needle.length();
for (int i = 0; i + m <= n; i++) {
boolean flag = true;
for (int j = 0; j < m; j++) {
if (haystack.charAt(i + j) != needle.charAt(j)) {
flag = false;
break;
}
}
if (flag) {
return i;
}
}
return -1;
}
}
Method 2 :KMP
class Solution {
public int strStr(String haystack, String needle) {
int n = haystack.length(), m = needle.length();
if (m == 0) {
return 0;
}
int[] pi = new int[m];
for (int i = 1, j = 0; i < m; i++) {
while (j > 0 && needle.charAt(i) != needle.charAt(j)) {
j = pi[j - 1];
}
if (needle.charAt(i) == needle.charAt(j)) {
j++;
}
pi[i] = j;
}
for (int i = 0, j = 0; i < n; i++) {
while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {
j = pi[j - 1];
}
if (haystack.charAt(i) == needle.charAt(j)) {
j++;
}
if (j == m) {
return i - m + 1;
}
}
return -1;
}
}
边栏推荐
- Solve the problem of repeated clicking of button uibutton
- [enlightenment -51]: since people are doomed to die, why should they live?
- 网络安全——文件上传竞争条件绕过
- FlinkTable&SQL(七)
- position: -webkit-sticky; /* for Safari */ position: sticky;
- 在LNMP架构中搭建Zabbix监控服务
- Chapter VI bus
- Network security -- man in the middle attack penetration test
- Flinktable & SQL (VI)
- How to verify the domain name after applying for SSL digital certificate?
猜你喜欢

【C语言笔记分享】——动态内存管理malloc、free、calloc、realloc、柔性数组

RHCE first operation

天然气潮流计算matlab程序

rhcsa第六次笔记

Network security - Web penetration testing

网络安全——文件上传竞争条件绕过

5年接触近百位老板,身为猎头的我,发现升职的秘密不过4个字

OWASP ZAP安全测试工具使用教程(高级)

Game thinking 04 summary: a summary of frame, state and physical synchronization (it was too long before, and now it's brief)

How to generate expected data? Emory University and others' latest "deep learning controllable data generation" review, 52 page PDF, covering 346 documents, comprehensively expounds the controllable g
随机推荐
Network security -- man in the middle attack penetration test
R语言使用epiDisplay包的tableStack函数制作统计汇总表格(基于目标变量分组的描述性统计、假设检验等)、设置by参数为目标变量、设置percent参数配置是否显示百分比信息
Browser type judgment
自动化运维之Ansible安装部署
数据修改插入
One problem encountered:
使用Activiti创建数据库表报错,
Solve the problem that the ARR containsobject method returns no every time
CSP2021 T1 廊桥分配
Matlab program for natural gas flow calculation
SQL server startup and shutdown job script
2021-07-09
Is it safe for Huatai Securities to open an account through channels? Is it formal
Why are there "two abstract methods" in the functional interface comparator?
Editor formula
Flink comprehensive case (IX)
Explain flex layout in detail
Get (min / max value) of (object array / array)
Detailed explanation of switch link aggregation [Huawei ENSP]
三层交换机配置MSTP协议详解【华为eNSP实验】