28. Find the Index of the First Occurrence in a String
Tags:
Easy
Skills:
String
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Problem
Bài toán yêu cầu tìm chỉ số đầu tiêm mà chuỗi con needle xuất hiện trong chuỗi haystack . Nếu không tồn tại, return -1 . Nếu needle là chuỗi rỗng, return 0
Approach
haystack từ 0 đến haystack.length - needle.length haystack với needle -1 Time and space complexity
haystack , m là độ dài needle Solution
1function strStr(haystack: string, needle: string): number {
2 if(needle.length === 0) return 0;
3 const n = haystack.length;
4 const m = needle.length;
5 for(let i =0; i <= n - m; i++) {
6 if(haystack.substring(i, i + m) === needle) {
7 return i
8 }
9 }
10
11 return -1
12};needle rỗng, return 0i từ 0 -> n - m i -> i + m i -1 Approach - Rabin-Karp
Là một thuật toán tìm