Given two integers A and B, the task is to generate and print a string str such that:
- str must only contain the characters ‘a’ and ‘b’.
- str has length A + B and the occurrence of character ‘a’ is equal to A and the occurrence of character ‘b’ is equal to B
- The sub-strings “aaa” or “bbb” must not occur in str.
Note that for the given values of A and B, a valid string can always be generated.
Input: A = 1, B = 2
“abb”, “bab” and “bba” are all valid strings.
Input: A = 4, B = 1
- If occurrence(a) > occurrence(b) then append “aab”
- If occurrence(b) > occurrence(a) then append “bba”
- If occurrence(a) = occurrence(b) then append “ab”
Since we reduce the difference between the occurrences of ‘a’ and ‘b’ by at most 1 in each iteration so “bba” and “aab” are guaranteed not to be followed by “aab” and “bba” respectively.
Below is the implementation of the above approach:
- Length of the smallest sub-string consisting of maximum distinct characters
- Maximum count of sub-strings of length K consisting of same characters
- Permutation of a string with maximum number of characters greater than its adjacent characters
- Min flips of continuous characters to make all characters same in a string
- String with k distinct characters and no same characters adjacent
- Generate all rotations of a given string
- Minimal moves to form a string by adding characters or appending string itself
- Create a new string by alternately combining the characters of two halves of the string in reverse
- Lexicographically smallest string formed by appending a character from the first K characters of a given string
- Minimum deletions from string to reduce it to string with at most 2 unique characters
- Generate random String of given size in Java
- Program to generate all possible valid IP addresses from given string
- Find the smallest window in a string containing all characters of another string
- Check whether second string can be formed from characters of first string
- Remove characters from the first string which are present in the second string
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.