Click here to see the full article post
@awaice for python solution, why need this judgement:
if not ans or ch1 != ans[-1]:
if ch1==ans[-1] happens, since ch1 and ch2 were already poped and will never be pushed back, the result will not be valid since some chars missing.
also "any(-nc > (len(S) + 1) / 2 for nc, x in pq)" has already excluded the invalid case, so will ch1==ans[-1] happen?
@ywh1988 The solution has been corrected, thanks.
if (ans.length() == 0 || mc1.letter != ans.charAt(ans.length() - 1))
Do we need this condition in approach 2?
In the current code, if happen those two characters will be ignored. So, Ans will be incorrect.
Testing Link for Google Google
@awice. The condition "if not ans or ch1 != ans[-1]:" is not necessary.
suppose in the previous iteration, ['a', 'b'] has been appended to ans. With the condition you are trying to say if in the current iteration, if 'b' has become the MOST common character, don't append it to ans since it will create a sequence of ['a', 'b', 'b'] which is invalid.
But in the previous iteration, 'a' is the MOST common character. With the counters of 'a' and 'b' both being decremented by 1, the current iteration, there is no way that 'b' will ever become the MOST common character.
So the condition above will always hold True and is not necessary. I have removed the condition and my answer gets AC too.
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.