You are given a string s
consisting of lowercase English letters. An adjacent group of characters is a group of consecutive characters that are all the same in the string. For example, in the string “abaaaacc”, the groups are ‘a’, ‘b’, ‘aaaa’, ‘cc’. The function longestUnequalGroupsSubsequence(s)
should return the longest subsequence where no two adjacent groups are equal.
s
with at least one character will be provided.def longestUnequalGroupsSubsequence(s: str) -> int:
if not s:
return 0
n = len(s)
prev_char = s[0]
groups = []
count = 1
for i in range(1, n):
if s[i] == prev_char:
count += 1
else:
groups.append(prev_char * count)
prev_char = s[i]
count = 1
# Add the last group
groups.append(prev_char * count)
# Initialize the longest subsequence count
longest_length = 1
current_length = 1
for i in range(1, len(groups)):
if groups[i] != groups[i - 1]:
current_length += 1
longest_length = max(longest_length, current_length)
else:
current_length = 1
return longest_length
# Example usage:
print(longestUnequalGroupsSubsequence("abaaaacc")) # Expected output: 4
m
is the number of groups, which in the worst case can be O(n).Therefore, the overall time complexity is O(n), where n
is the length of the string, which is efficient for the input size constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?