DEV Community

Debesh P.
Debesh P.

Posted on

28. Find the Index of the First Occurrence in a String | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/


Detailed Step-by-Step Explanation

https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/solutions/7446929/most-optimal-approach-interview-friendly-ua2e


leetcode 28


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;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)