Question: I need a better algorithm than what I already have, and also an explanation as to how it is better. This is the original question:

I need a better algorithm than what I already have, and also an explanation as to how it is better.

This is the original question:

Consider the problem of counting, in a given text, the number of substrings that start with an A and ends with a B. For example, there are four such substrings in CGHABDFGAGHAHGHBS. Assume all input and output is in upper case. 1. Design a brute-force algorithm for this problem and determine its efficiency class (order of growth). Implement a method to do this and a main method to run the program. 2. Design and implement a more efficient algorithm for this problem as a method and invoke it from the same main program as written above. In implementing your program, read in the input as shown (the first line is the string, the second line is the starting substring, and the third line is the second substring: SAMPLE INPUT: CGHABDFGAGHAHGHBS; A B; Your output will consist of a single integer, displaying the number of substrings: SAMPLE OUTPUT: 4

My algorithm method:

public static int subStringCount(String matchString) { int count = 0; for(int i = 0; i < matchString.length(); i++) { if(matchString.charAt(i) == 'A') { for(int j = i+1; j < matchString.length(); j++) { if(matchString.charAt(j) == 'B') { count++; } } } } return count; }

It works, but I need to figure out how to find a better algorithm that is better than O(n^2) which is what my algorithm above is running at. This is what I need help with. Thank you!

Language in Java please!

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!