Given a string S, we need to write a program to check if it is possible to construct the given string S by performing any of the below operations any number of times. In each step, we can:
- Add any character at the end of the string.
- or, append the string to the string itself.
The above steps can be applied any number of times. We need to write a program to print the minimum steps required to form the string.
Input : aaaaaaaa Output : 4 Explanation: move 1: add 'a' to form "a" move 2: add 'a' to form "aa" move 3: append "aa" to form "aaaa" move 4: append "aaaa" to form "aaaaaaaa" Input: aaaaaa Output: 4 Explanation: move 1: add 'a' to form "a" move 2: add 'a' to form "aa" move 3: add 'a' to form "aaa" move 4: append "aaa" to form "aaaaaa" Input: abcabca Output: 5
The idea to solve this problem is to use Dynamic Programming to count the minimum number of moves. Create an array named dp of size n, where n is the length of the input string. dp[i] stores the minimum number of moves that are required to make substring (0…i). According to the question there are two moves that are possible:
- dp[i] = min(dp[i], dp[i-1] + 1) which signifies addition of characters.
- dp[i*2+1] = min(dp[i]+1, dp[i*2+1]), appending of string is done if s[0…i]==s[i+1..i*2+1]
- Minimum splits in a binary string such that every substring is a power of 4 or 6.
- Program for longest common directory path
- Check if any valid sequence is divisible by M
- Converting one string to other using append and delete last operations
- Maximum difference of zeros and ones in binary string
- Minimum steps to delete a string after repeated deletion of palindrome substrings
- Minimum sum subsequence such that at least one of every four consecutive elements is picked
- Minimum and Maximum values of an expression with * and +
- Maximum sum subarray removing at most one element
- Wildcard Pattern Matching
- Minimum time to finish tasks without skipping two consecutive
- Transform One String to Another using Minimum Number of Given Operation
- Remove minimum elements from either side such that 2*min becomes more than max
- Maximum Product Cutting | DP-36
- Edit Distance | DP-5
The answer will be stored in dp[n-1] as we need to form the string(0..n-1) index-wise.
Below is the implementation of above idea:
Time Complexity : O(n2), where n is the length of input 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 firstname.lastname@example.org. 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.
Improved By : Mithun Kumar