Problem Link
https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/
Detailed Step-by-Step Explanation
Solution
class Solution {
public int strStr(String haystack, String needle) {
int n1 = haystack.length();
int n2 = needle.length();
if (n2 == 0) {
return -1;
}
for (int i = 0; i <= n1 - n2; i++) {
if (haystack.charAt(i) == needle.charAt(0)) {
if (compare(haystack, needle, i)) {
return i;
}
}
}
return -1;
}
private boolean compare(String haystack, String needle, int idx) {
int n1 = haystack.length();
int n2 = needle.length();
if (idx + n2 > n1) {
return false;
}
for (int i = 0; i < n2; i++) {
if (needle.charAt(i) != haystack.charAt(idx + i)) {
return false;
}
}
return true;
}
}

Top comments (0)