https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-
string/
28. Find the Index of the First Occurrence in a String
Given two strings needle and haystack, return the index of the first
occurrence of needle in haystack, or -1 if needle is not part of haystack.
在较长的A字串里面找B字串
Example 1:
Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Example 2:
Input: haystack = "leetcode", needle = "leeto"
Output: -1
Step:
0. 检查B字串empty
1. 从A字串开始跑
1-1. 检查是否符合B字串,否则break,从下个char重复1-1
1-2. 如果检查到跟B一样的字串(j == needle_size),
return检查起点(i of haystack_size)
2. 重复1都没有成功,return -1
Code:
impl Solution
{
pub fn str_str(haystack: String, needle: String) -> i32
{
if needle.is_empty()
{
return 0;
}
let haystack_size = haystack.len();
let needle_size = needle.len();
for i in 0..haystack_size
{
let mut j = 0;
while j < needle_size
{
if haystack.chars().nth(i + j) != needle.chars().nth(j)
{
break;
}
j += 1;
}
if j == needle_size
{
return i as i32;
}
}
return -1;
}
}
C++:
class Solution
{
public:
int strStr(string haystack, string needle)
{
if (needle.empty())
return 0;
int haystack_size = haystack.size();
int needle_size = needle.size();
for (int i = 0; i <= haystack_size - needle_size; i++)
{
int j;
for (j = 0; j < needle_size; j++)
{
if (haystack[i + j] != needle[j])
break;
}
if (j == needle_size)
return i;
}
return -1;
}
};