![]() |
VOOZH | about |
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:
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. Examples:
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:
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 the above idea:
4
Time Complexity: O(n2), where n is the length of the input string.
Auxiliary Space: O(n)