class Solution:
def balancedStringSplit(self, s: str) -> int:
answer = 0
l =0
r = 0
for sa in s:
if sa == "R":
l+=1
elif sa == "L":
r+=1
if(r==l):
answer+=1
print("I am answer")
return answer
String: “RLRRLLRLRL” → although the answer is 4, but shouldn’t the answer be 5 in this case. Could someone explain why the answer is coming out to be 4. Since the string has 5 R’s and 5 L’s.
The problem you have, is with the logic: on only four occasions (given the sequence RLRRLLRLRL) are l and r of an equal value and as such on only four occasions is the variable answer incremented.
There is a much simpler way to do this: you can use the .count() method, but maybe that’s not an option, for some reason?
To add: it splits out thus…
1:RL
2:RRLL
3:RL
4:RL
Thinking about this some more, are you sure that the answer should not be four, given that the balance of Ls and Rs, that is to say that the number of Ls and Rs on each side, only balances out four times?
actually now if I rethink you are correct, I was calculating it the wrong way in my mind I was thinking total number of R’s = 5 and total number of L’s = 5, hence I can make 5 combinations in total but that is not how it works. the combinations are created on the basis of what is being read from the string at one particular point of time.
Actually Thank you so much! you really made this question very easy and nicely understandable to me.