Skip to content

How to ReImplement strStr() in Java

What we want to achieve

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

How to code this

class Solution { public int strStr(String haystack, String needle) { // If needle is an empty string if (needle.isEmpty()) return ; // If the needle is not within the haystack if (!haystack.contains(needle)) return -1; // declare an index and the needle's length int index = ; int len = needle.length(); // loop through the hackstack minus the needle's length for (int i = ; i <= haystack.length() - len; i++) { // compare the needle with the hackstack new string // created from using substring, start->end if (haystack.substring(i, i + len).equals(needle)) { // set the index and exit index = i; break; } } return index; } }
Code language: Java (java)

See also  How to solve the House Robber Challenge in Java
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x