Given two strings of equal lengths str1 and str2 consisting of characters ‘a’ and ‘b’ only. The followig operations can be performed on str1:
- Any character can be changed from ‘a’ to ‘b’ or from ‘b’ to ‘a’ with 1 unit cost.
- Any two characters str1[i] and str1[j] can be swapped with cost |i – j|.
The task is to find the minimum cost required to convert str1 to str2.
Input: str1 = “abb”, str2 = “baa”
Swap(str1, str1), str1 = “bab” and cost = 1
Change str1 = ‘b’ to ‘a’, str1 = “baa” and cost = 2
Input: str1 = “abab”, str2 = “aabb”
Approach: It can be observed that swapping will only be performed on consecutive characters because if the characters are not consecutive then the cost of swapping will be ≥ 2 which will give cost greater than or equal to the cost of changing those characters using the operation of the first type. Now, for every two consecutive characters if they are different in both the string then swap these characters incurring 1 unit cost as compares to 2 unit cost when both of them are changed separately. Else change the character which is different in both the strings (either the current or the next). Finally, print the calculated cost.
Below is the implementation of the above approach:
- Check whether str1 can be converted to str2 with the given operations
- Count of characters in str1 such that after deleting anyone of them str1 becomes str2
- Largest substring of str2 which is a prefix of str1
- Generate all possible strings such that char at index i is either str1[i] or str2[i]
- Maximum number of times str1 appears as a non-overlapping substring in str2
- Minimum cost to reach a point N from 0 with two different operations allowed
- Minimum cost to sort strings using reversal operations of different costs
- Minimum cost to convert string into palindrome
- Minimum given operations required to convert a given binary string to all 1's
- Minimum reduce operations to convert a given string into a palindrome
- Minimum operations required to convert a binary string to all 0s or all 1s
- Minimum number of operations to convert a given sequence into a Geometric Progression
- Minimum number of given operations required to convert a string to another string
- Minimum cost to modify a string
- Minimum cost to connect all cities
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.