Tuesday, May 16, 2017

Needle in HayStack

Problem Statement

Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Link to GitHub JavaCode
Link to GitHub JavaScript Code




Understanding the problem statement
This question is confusing. lets understand the problem
The fundamental string searching (matching) problem is defined as follows: given two strings – a text and a pattern, determine whether the pattern appears in the text. The problem is also known as “the needle in a haystack problem.”

Example:
Example 1
s="strstr"
needle="Str"
output=-1

Example 2
s="strStr"
needle="Str"
output=3

Example 3
s="strstr"
needle="str"
output=0

Solution

  • We need 2 loops with i and j counters
  • We need compare the characters from actual string with that to the needle.
  • We would only increment j counter if we find the character in the string matches character in the needle
  • If needle length matches j counters we need to return i else return -1 
public static int get(String haystack, String needle)
 {
  for(int i=0;;i++){
   for(int j=0;;j++){
    if(j==needle.length()) return i;
    if(i+j==haystack.length()) return -1;
    if(needle.charAt(j)!=haystack.charAt(i+j))
     {break;}
         }
  }
 }

Iteration


No comments:

Post a Comment