


Add the minimum subsequence required to append string A to obtain string B
In this problem, we need to construct str2 using the subsequence of str1. To solve this problem, we can find the subsequence of str1 such that it covers the substring with the maximum length of str2. Here we will learn two different ways to solve the problem.
Problem Statement – We are given two strings of different lengths: str1 and str2. We need to construct str2 from str1 according to the following conditions.
Pick any subsequence from str1 and append it to a new string (initially empty).
We need to return the minimum number of operands required to construct str2, and print -1 if str2 cannot be constructed.
Example
Input– str1 = “acd”, str2 = “adc”
Output– 2
illustrate
The first subsequence in str1 is "ad". So, our string could be "ad".
After that, we can get the "c" subsequence from str1 and append it to "ad" to make it "adc".
Input– str1 = "adcb", str2 = "abdca"
Output– 3
illustrate
The first subsequence is "ab" in str1.
After that, we can get the "dc" string and the resulting string will be "abdc"
Next, we can use the "a" subsequence to generate the final string "abdca".
method 1
In this method we will iterate over str1 to find multiple subsequences and append them to the resulting string.
algorithm
Define the "arr" array of length 26 and initialize all elements to 0 to store the presence of characters in str1.
Iterate str1 and update the value of the array element according to the ASCII value of the character
Define the "last" variable and initialize it with -1 to track the last element visited. Additionally, define the "cnt" variable and initialize it to 0 to store the operation count.
Start using a loop to traverse str2.
If the current character is not in str1, return -1.
Initialize the "j" variable using the "last 1" value.
Use a while loop to iterate until the value of j is less than len, and str1[j] is not equal to the character
If the value of 'j' is greater than 'len', we traverse 'str1'. Increase the value of the 'cnt' variable, initialize 'last' to -1 because we need to iterate over 'str1' again, decrease the value of 'I' by 1 because we need to consider the current character again, continue using the 'continue' keyword Iterate.
Update the value of the "last" variable to "j".
Return "cnt 1" after all iterations of the loop are completed. Here, we need to add "1" to "cnt" because we are not considering the last operation.
Example
#include <iostream> using namespace std; // function to count the minimum number of operations required to get string str2 from subsequences of string str1. int minOperations(string str1, string str2){ int len = str1.length(); // creating an array of size 26 to store the presence of characters in string str1. int arr[26] = {0}; // storing the presence of characters in string str1. for (int i = 0; i < len; i++){ arr[str1[i] - 'a']++; } // store the last iterated index of string str1. int last = -1; // to store the count of operations. int cnt = 0; for (int i = 0; i < str2.length(); i++){ char ch = str2[i]; // if the character is not present in string str1, then return -1. if (arr[ch - 'a'] == 0){ return -1; } // start iterating from the jth index of string str1 to find the character ch. int j = last + 1; while (j < len && str1[j] != ch){ j++; } // if j is equal to the length of string str1, then increment the count, set last to -1, and decrement i. if (j >= len){ cnt++; last = -1; --i; continue; } // set last to j. last = j; } // return cnt + 1 as we haven't counted the last operation. return cnt + 1; } int main(){ string str1 = "acd", str2 = "adc"; int operations = minOperations(str1, str2); cout << "Minimum number of operations required to create string B from the subsequences of the string A is: " << operations << "\n"; return 0; }
Output
Minimum number of operations required to create string B from the subsequences of the string A is: 2
Time complexity – O(N*M), where N is the length of str2 and M is the length of str1.
Space complexity - O(1), since we don't use any dynamic space.
Method 2
In this method, we will use mapping and collection data structures to improve the efficiency of the above method. The logic to solve the problem is the same as above.
algorithm
Define "chars_mp" to store char -> sets{} as key-value pairs.
In the mapping, store the index set where specific characters exist in the str1 string
Define "last" and "cnt" variables
Start traversing str2. If the size of the collection containing the current character index is zero, -1 is returned.
Find the upper limit of "last" in the current character index set.
If the upper limit is not found, increase the value of "cnt" by 1, set "last" to -1, decrease the value of "I" by 1, and use the continue keyword. p>
Update the value of the "last" variable.
After the loop iteration is completed, return the value of the ‘cnt’ variable
Example
#include <iostream> #include <map> #include <set> using namespace std; // function to count the minimum number of operations required to get string str2 from subsequences of string str1. int minOperations(string str1, string str2){ // Length of string str1 int len = str1.length(); // creating the map to store the set of indices for each character in str1 map<char, set<int>> chars_mp; // Iterate over the characters of str1 and store the indices of each character in the map for (int i = 0; i < len; i++){ chars_mp[str1[i]].insert(i); } // store the last visited index of str1 int last = -1; // Stores the required count int cnt = 1; // Iterate over the characters of str2 for (int i = 0; i < str2.length(); i++){ char ch = str2[i]; // If the set of indices of str2[i] is empty, then return -1 if (chars_mp[ch].size() == 0){ return -1; } // If the set of indices of str2[i] is not empty, then find the upper bound of last in the set of indices of str2[i] // It finds the smallest index of str2[i] which is greater than last auto it = chars_mp[ch].upper_bound(last); // If the upper bound is equal to the end of the set, then increment the count and update last to -1 if (it == chars_mp[ch].end()){ last = -1; cnt++; // Decrement I by 1 to process the current character again --i; continue; } // Update last to the current index last = *it; } return cnt; } int main(){ string str1 = "adcb", str2 = "abdca"; int operations = minOperations(str1, str2); cout << "Minimum number of operations required to create string B from the subsequences of the string A is: " << operations << "\n"; return 0; }
Output
Minimum number of operations required to create string B from the subsequences of the string A is: 3
Time Complexity – O(N*logN), since we iterate over str2 and find the upper bound of the “last” index in the loop.
Space complexity – O(N) because we use a map to store the character index.
The above is the detailed content of Add the minimum subsequence required to append string A to obtain string B. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Players can obtain Lucia's Crimson Abyss when playing in Battle Double Pamish. Many players don't know how to obtain Lucia's Crimson Abyss. Players can obtain it through research and development, or redeem it at the Phantom Pain Cage store. How to obtain R&D for Battle Double Pamish Lucia Crimson Abyss 1. Players can obtain it by drawing from the R&D system, which includes the base card pool, the theme limited card pool and the destiny limited card pool. 2. Revealed in these card pools The basic drop rate of Sia Crimson Abyss is 1.50%, but if the player draws Lucia Crimson Abyss from the card pool, the drop rate will increase to 1.90%. Redemption in the Phantom Pain Cage Store 1. Players can redeem fragments of Lucia Crimson Abyss by using Phantom Pain Scars in the Phantom Pain Cage Store. 2. You can redeem up to 30 fragments every week.

It is very important to obtain administrator rights in the Win11 system, because administrator rights allow users to perform various operations in the system, such as installing software, modifying system settings, etc. Obtaining administrator rights in Win11 system can be achieved through the following methods: The first method is through user account control settings. In the Win11 system, User Account Control is a function used to manage user permissions. Through it, users can adjust their permission levels. To obtain administrator rights, users can enter the "Settings" interface and select "

Title: How to determine whether a string ends with a specific character in Golang. In the Go language, sometimes we need to determine whether a string ends with a specific character. This is very common when processing strings. This article will introduce how to use the Go language to implement this function, and provide code examples for your reference. First, let's take a look at how to determine whether a string ends with a specified character in Golang. The characters in a string in Golang can be obtained through indexing, and the length of the string can be

Detailed explanation of the method of converting int type to string in PHP In PHP development, we often encounter the need to convert int type to string type. This conversion can be achieved in a variety of ways. This article will introduce several common methods in detail, with specific code examples to help readers better understand. 1. Use PHP’s built-in function strval(). PHP provides a built-in function strval() that can convert variables of different types into string types. When we need to convert int type to string type,

1. First open pycharm and enter the pycharm homepage. 2. Then create a new python script, right-click - click new - click pythonfile. 3. Enter a string, code: s="-". 4. Then you need to repeat the symbols in the string 20 times, code: s1=s*20. 5. Enter the print output code, code: print(s1). 6. Finally run the script and you will see our return value at the bottom: - repeated 20 times.

Torret is the spirit horse in the game Elden's Circle. Many players don't know how to obtain Torret of Elden's Circle. To summon Torret, players need to obtain the spirit horse whistle, which is equipped in the shortcut bar. After that, use the shortcut keys to summon the spirit horse Torret. How to obtain Torret of Eldon's Ring? Answer: You need to obtain the Whistle of the Spirit Horse. 1. Players need to obtain the Spirit Horse Whistle to summon Torret. 2. Players go from the novice birth point to the blessing point in front of the Storm Road, sit down by the campfire, and the heroine [Melina] will appear, and she will give you a [Spirit Horse Whistle] ring. 3. After players equip the "Spirit Horse Whistle" to the shortcut bar and then use the Spirit Horse Whistle, they can summon the soul of Thoret's horse. 4. After riding the spirit horse Torret, you can perform a double jump. You can jump while walking but cannot jump.

How to check if a string starts with a specific character in Golang? When programming in Golang, you often encounter situations where you need to check whether a string begins with a specific character. To meet this requirement, we can use the functions provided by the strings package in Golang to achieve this. Next, we will introduce in detail how to use Golang to check whether a string starts with a specific character, with specific code examples. In Golang, we can use HasPrefix from the strings package

Go language is a powerful and flexible programming language that provides rich string processing functions, including string interception. In the Go language, we can use slices to intercept strings. Next, we will introduce in detail how to intercept strings in Go language, with specific code examples. 1. Use slicing to intercept a string. In the Go language, you can use slicing expressions to intercept a part of a string. The syntax of slice expression is as follows: slice:=str[start:end]where, s
