28. Find the Index of the First Occurrence in a String(Solution || Leetcode medium || Java)

Palakkgoyal
1 min readNov 26, 2022

--

Runtime: 0 ms, faster than 100.00% of Java online submissions for Find the Index of the First Occurrence in a String.

Memory Usage: 40.4 MB, less than 84.90% of Java online submissions for 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.

Example 1:

Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Explanation: "sad" occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.

Example 2:

Input: haystack = "leetcode", needle = "leeto"
Output: -1
Explanation: "leeto" did not occur in "leetcode", so we return -1.

Constraints:

  • 1 <= haystack.length, needle.length <= 104
  • haystack and needle consist of only lowercase English characters.

SOLUTION:

class Solution {
public int strStr(String haystack, String needle) {
int h = haystack.length();
int n = needle.length();

if(h < n){
return -1;
}

//We will use two pointers that will search for needle as a substring
int j = 0;

for(int i = n - 1; i < h; i++){
if( haystack.substring(j,i+1).equals(needle)){
return j;
}
else{
j++;
}
}

return -1;
}
}

Thank you for reading. If you have any queries then, please let me know in the comment section. I will surely be responsive toward it.

--

--

Palakkgoyal
Palakkgoyal

Written by Palakkgoyal

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.

No responses yet