LeetCode 28: Find the Index of the First Occurrence in a String Solution
Master LeetCode problem 28 (Find the Index of the First Occurrence in a String), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
28. Find the Index of the First Occurrence in a String
Problem Explanation
Explanation:
To find the index of the first occurrence of the needle string in the haystack string, we can iterate through the haystack string character by character. At each position, we check if the substring starting from that position matches the needle string. If a match is found, we return the current index as the result. If no match is found, we continue to the next character in the haystack string. If we reach the end of the haystack string without finding a match, we return -1.
-
Algorithm:
- Iterate through the
haystackstring character by character. - Check if the substring starting from the current position matches the
needlestring. - If a match is found, return the current index.
- If no match is found, continue to the next character.
- If no match is found after iterating through the entire
haystackstring, return -1.
- Iterate through the
-
Time Complexity: O((m-n)*n) where m is the length of
haystackand n is the length ofneedle. -
Space Complexity: O(1)
:
Solution Code
class Solution {
public int strStr(String haystack, String needle) {
if (needle.isEmpty()) {
return 0;
}
for (int i = 0; i <= haystack.length() - needle.length(); i++) {
if (haystack.substring(i, i + needle.length()).equals(needle)) {
return i;
}
}
return -1;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 28 (Find the Index of the First Occurrence in a String)?
This page provides optimized solutions for LeetCode problem 28 (Find the Index of the First Occurrence in a String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 28 (Find the Index of the First Occurrence in a String)?
The time complexity for LeetCode 28 (Find the Index of the First Occurrence in a String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 28 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 28 in Java, C++, or Python.