
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find shortest string after removing different adjacent bits in Python
Suppose we have a binary string s, we can delete any two adjacent letters if they are different. Finally, we have to find the length of the smallest string that we can get if we are able to perform this operation as many times as we want.
So, if the input is like s = "1100011", then the output will be 1, as After deleting "10" we get "10011", then again delete "10", it will be "011", then delete "01", it will have left 1.
To solve this, we will follow these steps −
- stack := a new list
- for each c in s, do
- if stack is empty or top of stack is same as c, then
- push c into stack
- otherwise when top of stack is not same as c, then
- pop element from stack
- if stack is empty or top of stack is same as c, then
- return element count in stack
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, s): stack = [] for c in s: if not stack or stack[-1] == c: stack.append(c) elif stack[-1] != c: stack.pop() return len(stack) ob = Solution() print(ob.solve("1100011"))
Input
"1100011"
Output
1
- Related Articles
- Program to find string after removing consecutive duplicate characters in Python
- Program to find mean of array after removing some elements in Python
- Removing letters to make adjacent pairs different using JavaScript
- Removing adjacent duplicates from a string in JavaScript
- Program to find maximum difference of adjacent values after deleting k numbers in python
- Program to find longest number of 1s after swapping one pair of bits in Python
- Program to find maximum binary string after change in python
- Program to find shortest sublist so after sorting that entire list will be sorted in Python
- Program to find minimum possible integer after at most k adjacent swaps on digits in Python
- Program to find lexicographically smallest string after applying operations in Python
- Program to find length of shortest supersequence in Python
- Program to find number of sequences after adjacent k swaps and at most k swaps in Python
- Program to find min length of run-length encoding after removing at most k characters in Python
- Removing nth character from a string in Python program
- Program to find maximum adjacent absolute value sum after single reversal in C++

Advertisements