B - 文字列の整理 / Organizing Strings 解説 by admin
gpt-5.3-codexOverview
This is a problem where you repeatedly remove pairs of adjacent identical characters, aiming to minimize the final string length. This problem can be solved by implementing the following process with a stack: “scan from left to right, and if the current character matches the most recent unremoved character, cancel them out.” This yields the minimum length in a single pass.
Analysis
The two key observations are:
- You can only remove “adjacent identical characters”
- When looking at a character, the only thing that matters is “the current tail (the most recently remaining character)”
For example, consider abba:
- Keep
a→a - Keep
b→ab - The next
bmatches the tailb, so both are removed →a - The next
amatches the taila, so both are removed → empty
The final length is 0.
A naive approach of “repeatedly finding a removable pair and deleting it” would require searching and string reconstruction for each deletion, leading to \(O(N^2)\) in the worst case. Since \(|S| \le 10^6\), this is too slow.
Instead, we use a stack.
- Process characters one by one from left to right
- If the top of the stack matches the current character,
pop(the two characters cancel out) - Otherwise,
append(keep it as undecided)
With this approach, each character is pushed at most once and popped at most once, making it efficient. Moreover, this process produces the same result as optimally repeating the actual deletions.
Algorithm
- Prepare an empty stack
stack. - Iterate through string
Sfrom left to right, examining each characterc:- If
stackis not empty andstack[-1] == c, thenstack.pop(). - Otherwise,
stack.append(c).
- If
- After processing all characters, output
len(stack).
Concrete example abccbd:
a→[a]b→[a,b]c→[a,b,c]c(same) →[a,b]b(same) →[a]d→[a,d]
The final length is 2.
Complexity
- Time complexity: \(O(N)\)
- Space complexity: \(O(N)\)
(\(N = |S|\))
Implementation Notes
In Python, using a list as a stack with
append/popis sufficiently fast.Since the input size can be large, it is safer to use
sys.stdin.readline().strip().Since we only need to output the length,
print(len(stack))is all that’s needed.Source Code
import sys
def main():
s = sys.stdin.readline().strip()
stack = []
for c in s:
if stack and stack[-1] == c:
stack.pop()
else:
stack.append(c)
print(len(stack))
if __name__ == "__main__":
main()
This editorial was generated by gpt-5.3-codex.
投稿日時:
最終更新: