LeetCode 28: Find the Index of the First Occurrence in a String
LeetCode 28 Solution 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
haystack
string character by character. - Check if the substring starting from the current position matches the
needle
string. - 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
haystack
string, return -1.
- Iterate through the
-
Time Complexity: O((m-n)*n) where m is the length of
haystack
and n is the length ofneedle
. -
Space Complexity: O(1)
:
LeetCode 28 Solutions in Java, C++, Python
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;
}
}
Interactive Code Editor for LeetCode 28
Improve Your LeetCode 28 Solution
Use the editor below to refine the provided solution for LeetCode 28. Select a programming language and try the following:
- Add import statements if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.
Loading editor...