title: Daily practice (37): implement strStr()
categories:[Swords offer]
tags:[Daily practice]
date: 2022/03/21
Daily practice (37): Implement strStr()
Implement the strStr() function.
Given two strings haystack and needle, please find the first position of the needle string in the haystack string (the subscript starts from 0). Returns -1 if not present.
illustrate:
What value should we return when needle is the empty string? This is a good question to ask in an interview.
For this problem, we should return 0 when needle is the empty string. This matches C's strstr() and Java's indexOf() definitions.
Example 1:
Input: haystack = "hello", needle = "ll"
output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
output: -1
Example 3:
Input: haystack = "", needle = ""
output: 0
hint:
0 <= haystack.length, needle.length <= 5 * 104
haystack and needle consist only of lowercase English characters
Source: LeetCode
Link: https://leetcode-cn.com/problems/implement-strstr
Method 1: Double pointer method (brute force solution)
Thought analysis
- Judging whether it is equal, the synchronization moves backward
- Unequal return start position, i+1, j=0;
int strStr(string haystack, string needle) {
int i = 0;
int j = 0;
while (haystack[i] != '\0' && needle[j] != '\0') {
if (needle[j] == haystack[i]) {//判断是否相等
j++;
i++;
} else { //不相等退回开始的位置,i+1,j=0;
i = i - j + 1;
j = 0;
}
}
if (j == needle.length()) { //j为步长
return i-j;
}
return -1;
}
Method 2: find function
int strStr(string haystack, string needle) {
if (needle.size() == 0) {
return 0;
}
return haystack.find(needle);
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。