Given a string of ‘0’, ‘1’ and ‘2’. The task is to find the minimum number of replacements such that the adjacent characters are not equal.
Input: s = “201220211”
Resultant string after changes is 201210210
Input: s = “0120102”
Approach: The problem has been solved using a greedy approach in the previous post. In this post, we will discuss a Dynamic Programming approach to solve the same problem. Create a function charVal which returns 0, 1 or 2 depending on the character.
A recursive function is made which calls the charVal function to get the i-th value, and if this is equal to the previous one, then only the other two states (1 or 2, 0 or 1, 0 or 2) is used at i-th character. If it is not equal to the previous one, no changes are made. A dp array is used for memoization. The base case is when all the positions are filled. If any of the state is re-visited, then return the value that is stored in dp array. DP[i][j] means that i-th position is filled with j-th character.
Below is the implementation of the above problem:
- Minimum replacements to make adjacent characters unequal in a ternary string
- Minimum number of replacements to make the binary string alternating | Set 2
- Minimum characters to be added at front to make string palindrome
- Minimum replacements such that the difference between the index of the same characters is divisible by 3
- Minimum number of characters to be removed to make a binary string alternate
- Permutation of a string with maximum number of characters greater than its adjacent characters
- Rearrange the characters of the string such that no two adjacent characters are consecutive English alphabets
- Convert string X to an anagram of string Y with minimum replacements
- String with k distinct characters and no same characters adjacent
- Form lexicographically smallest string with minimum replacements having equal number of 0s, 1s and 2s
- Min flips of continuous characters to make all characters same in a string
- Rearrange characters in a string such that no two adjacent are same
- C program to swap adjacent characters of a String
- Rearrange characters in a string such that no two adjacent are same using hashing
- Minimum operations to make frequency of all characters equal K
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.