Question

Task Algorithms: Pattern Matching (in java) Write a program that gets two strings from user, size...

Task Algorithms: Pattern Matching (in java)

Write a program that gets two strings from user, size and pattern, and checks if pattern exists inside size, if it exists then program returns index of first character of pattern inside size, otherwise it returns -1.

The method should not use built-in methods such as indexOf , find, etc. Only charAt and length are allowed to use.

Analyze the time complexity of your algorithm.

Your solution is not allowed to be> = O (m * n), it should be O (n) (where n is the length of the string being searched).

Hint:
The most intuitive solution will be two loops, one inside the other. This will not give O (N) behavior. It holds with one for loop; one index that runs through the string where we search and another index for the substring.

Feel free to solve the problem by implementing "brute force" / naive solution (the one with two loops) first, based on this you can solve the problem by reducing to just a loop and a bit smarter code.

Hint / partial pseudo code for an O (n) solution:
A counter k keeps track of the number of characters with a match, when this is equal to the length of the pattern we have a match

k = 0; 
for (iterates over the string we are searching in, from index 0) 
  if (k == length pattern) 
    returns index of start match 
  else 
    if characters in search string match characters in pattern 
      k ++; 
    else 
      k = 0;

..and then we have to treat a special case if k was incremented but for the loop terminated


Extra, as a challenge: Why not try to understand, and then implement the Boyer-Moore-Horspool algorithm?

0 0
Add a comment Improve this question Transcribed image text
Answer #1

// Recursive Java program to check if a string
// is subsequence of another string
import java.io.*;

class SubSequence
{
   // Returns true if str1[] is a subsequence of str2[]
   // m is length of str1 and n is length of str2
   static boolean isSubSequence(String str1, String str2, int m, int n)
   {
       // Base Cases
       if (m == 0)
           return true;
       if (n == 0)
           return false;
          
       // If last characters of two strings are matching
       if (str1.charAt(m-1) == str2.charAt(n-1))
           return isSubSequence(str1, str2, m-1, n-1);

       // If last characters are not matching
       return isSubSequence(str1, str2, m, n-1);
   }
  
   // Driver program
   public static void main (String[] args)
   {
       String str1 = "gksrek";
       String str2 = "geeksforgeeks";
       int m = str1.length();
       int n = str2.length();
       boolean res = isSubSequence(str1, str2, m, n);
       if(res)
           System.out.println("Yes");
       else
           System.out.println("No");
   }
}

// Iterative Java program to check if a string
// is subsequence of another string
import java.io.*;

class GFG {
  
   // Returns true if str1[] is a subsequence
   // of str2[] m is length of str1 and n is
   // length of str2
   static boolean isSubSequence(String str1,
                   String str2, int m, int n)
   {
       int j = 0;
      
       // Traverse str2 and str1, and compare
       // current character of str2 with first
       // unmatched char of str1, if matched
       // then move ahead in str1
       for (int i = 0; i < n && j < m; i++)
           if (str1.charAt(j) == str2.charAt(i))
               j++;

       // If all characters of str1 were found
       // in str2
       return (j == m);
   }
  
   // Driver program to test methods of
   // graph class
   public static void main (String[] args)
   {
       String str1 = "gksrek";
       String str2 = "geeksforgeeks";
       int m = str1.length();
       int n = str2.length();
       boolean res = isSubSequence(str1, str2, m, n);
      
       if(res)
           System.out.println("Yes");
       else
           System.out.println("No");
   }
}


Add a comment
Know the answer?
Add Answer to:
Task Algorithms: Pattern Matching (in java) Write a program that gets two strings from user, size...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • If the length of the array P is 4 and the length of the array T...

    If the length of the array P is 4 and the length of the array T is 14, how many shifts of P need to be performed in the string searching algorithm? a. 9 b. 10 c. 11 d. 12 What is the best case for the naive string search algorithm? a. The first character of the pattern P isn't present in text T b. All characters in pattern P are different c. All characters in text T are different...

  • Please read the problem carefully and answer the 2 questions below code: /***************************************************************** * Program: palindrome.c...

    Please read the problem carefully and answer the 2 questions below code: /***************************************************************** * Program: palindrome.c * * Purpose: implements a recursive function for determining *   if a string is a palindrome * * Authors: Steven R. Vegdahl, Tammy VanDeGrift, Martin Cenek * *****************************************************************/ #include #include #include /***************************************************************** * is_palindrome - determines whether a string of characters is a palindrome * * calling sequence: *    result = is_palindrome(str, first_index, last_index) * * parameters - *    str - the string to test *    first_index -...

  • Use c-strings for the following project: Write a C++ program that declares an array containing up...

    Use c-strings for the following project: Write a C++ program that declares an array containing up to a maximum of 20 sentences, each sentence of maximum 81 characters long, using c-strings. Continue reading sentences from the user and store them in the array of sentences, until the user enters a NULL string for the sentence or 20 sentences have been entered. Then, one by one, display each sentence entered by the user and present the following menu of operations on...

  • Java Programming Write a program to find the number of comparison using binarySearch and the sequentialSearch...

    Java Programming Write a program to find the number of comparison using binarySearch and the sequentialSearch algorithms as follows: Suppose list is an array of 2500 elements. 1. Use a random number generator to fill list; 2. Use a sorting algorithm to sort list; 3. Search list for some items as follows: a) Use the binary search algorithm to search list (please work on SearchSortAlgorithms.java and modify the algorithm to count the number of comparisons) b) Use the sequential search...

  • 0. Introduction. This involves designing a perfect hash function for a small set of strings. It...

    0. Introduction. This involves designing a perfect hash function for a small set of strings. It demonstrates that if the set of possible keys is small, then a perfect hash function need not be hard to design, or hard to understand. 1. Theory. A hash table is an array that associates keys with values. A hash function takes a key as its argument, and returns an index in the array. The object that appears at the index is the key’s...

  • Java StringNode Case Study: Rewrite the following methods in the StringNode class shown below. Leave all...

    Java StringNode Case Study: Rewrite the following methods in the StringNode class shown below. Leave all others intact and follow similar guidelines. The methods that need to be changed are in the code below. - Rewrite the indexOf() method. Remove the existing recursive implementation of the method, and replace it with one that uses iteration instead. - Rewrite the isPrefix() method so that it uses iteration. Remove the existing recursive implementation of the method, and replace it with one that...

  • !!!!!!!Java!!!!! When you are confident that your methods work properly and that you can generate random...

    !!!!!!!Java!!!!! When you are confident that your methods work properly and that you can generate random text with my generateText method, you can move on to the second step. Create a third class called Generator within the cs1410 package. Make class. This class should have a main method that provides a user interface for random text generation. Your interface should work as follows: Main should bring up an input dialog with which the user can enter the desired analysis level...

  • Lab 2: (one task for Program 5): Declare an array of C-strings to hold course names,...

    Lab 2: (one task for Program 5): Declare an array of C-strings to hold course names, and read in course names from an input file. Then do the output to show each course name that was read in. See Chapter 8 section on "C-Strings", and the section "Arrays of Strings and C-strings", which gives an example related to this lab. Declare the array for course names as a 2-D char array: char courseNames[10] [ 50]; -each row will be a...

  • Topics: About Java What is a compiler, and what does it do? Characteristics of the languageStrongly...

    Topics: About Java What is a compiler, and what does it do? Characteristics of the languageStrongly typed and statically typed Everything has a data type & data types must be declared Case sensitive Object oriented System.out.print() vs. System.out.println() How to use the Scanner class to obtain user input Data typesWhat are they? Know the basic types like: int, double, boolean, String, etc. Variables What is a variable? Declarations Initialization Assignment Constants Reserved words like: What is a reserved word? Examples:...

  • Suppose we are given two sorted arrays (nondecreasing from index 1 to index n) X[1] ·...

    Suppose we are given two sorted arrays (nondecreasing from index 1 to index n) X[1] · · · X[n] and Y [1] · · · Y [n] of integers. For simplicity, assume that n is a power of 2. Problem is to design an algorithm that determines if there is a number p in X and a number q in Y such that p + q is zero. If such numbers exist, the algorithm returns true; otherwise, it returns false....

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT