For example, there are four such substrings in CABAAXBYA.
The original brute force algorithm that I used was, Using an outer for loop, whenever I encounter an A, I go inside another for loop to check if there's a B present or not. If a B is found, I increment the count. Finally, the value stored in the count variable yields the required result.
I came across a point while reading about String matching algorithms, when you traverse right to left rather than left to right, your algorithm is more efficient but here the substring isn't given as a parameter to the function that you would be using to compute the required value.
My question is if I traverse the string from right to left instead of left to right, will it make my algorithm more efficient in any case?
Python String count() function is an inbuilt function in python programming language that returns the number of occurrences of a substring in the given string. Parameters: The count() function has one compulsory and two optional parameters.
Total number of substrings = n + (n - 1) + (n - 2) + (n - 3) + (n - 4) + ……. + 2 + 1. So now we have a formula for evaluating the number of substrings where n is the length of a given string.
The total number of substrings formed by string of length N is (N*(N+1))/2, initialise count as (N*(N+1))/2.
Here is one way in which iterating backwards through the string could result in O(n) computation instead of your original O(n^2) work:
A = "CABAAXBYA"
count = 0 # Number of B's seen
total = 0
for a in reversed(A):
if a=='B':
count += 1
elif a=='A':
total += count
print total
This works by keeping track in count of the number of B's to the right of the current point.
(Of course, you could also get the same result with forwards iteration by counting the number of A's to the left instead:
count = 0 # Number of A's seen
total = 0
for a in A:
if a=='A':
count += 1
elif a=='B':
total += count
print total
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With