Python Largest String
def largest_string(s: str) -> str:
chars = list(s)
length = len(chars)
# instead of raising; this helper preserves that read behavior so the
# lookahead checks below can't index past the end of the list.
def char_at(idx: int) -> str:
return chars[idx] if 0 <= idx < length else ""
cur = ""
i = length - 1
while i >= 0:
cur = char_at(i) + cur
if len(cur) == 3:
if cur == "abb":
chars[i] = "b"
chars[i + 1] = "a"
chars[i + 2] = "a"
if char_at(i + 4) == "b":
i += 4 + 1
elif char_at(i + 3) == "b":
i += 3 + 1
elif chars[i + 2] == "b":
i += 2 + 1
if char_at(i + 1) == "b":
i += 1 + 1
else:
i += 1
cur = ""
i -= 1
return "".join(chars)
This builds the biggest valid string it can under the challenge rules by always choosing the best next character it is allowed to use.