# Shortest Way to Form String in C++

C++Server Side ProgrammingProgramming

Suppose we have a string, we can form a subsequence of that string by deleting some number of characters (possibly no deletions). So if there is two strings source and target, we have to find the minimum number of subsequences of source such that their concatenation equals target. If the task is impossible, then return -1. So if source is “abc” and target is “abcbc”, then the output will be 2.

To solve this, we will follow these steps −

• Define a string called possible, this will take s and t as input

• create a map m

• for each character c in s mark m[c] := 1

• for each character c in t, if m[c] is 0, then return false

• return true

• Now from the main method, do the following −

• ssz := size of s and tsz := size of t

• create a map m of character type key and array type value

• for i in range 0 to ssz

• insert i into m[s[i]]

• pre := -1 and ret := 1

• for i in range 0 to tsz

• if t[i] is not present in m, return -1

• v := m[t[i]]

• set i := index of element in v, that is greater than pre

• if i is not the end of the list

• increase ret by 1 and pre := v[0]

• otherwise pre := v[i]

• return ret

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool possible(string s, string t){
map <char, int> m;
for(int i = 0; i < s.size(); i++){
m[s[i]] = 1;
}
for(int i = 0; i < t.size(); i++){
if(!m[t[i]])return false;
}
return true;
}
int shortestWay(string s, string t) {
int ssz = s.size();
int tsz = t.size();
map <char, vector <int> > m;
for(int i = 0; i < ssz; i++){
m[s[i]].push_back(i);
}
int pre = -1;
int ret = 1;
for(int i = 0; i < tsz; i++){
if(!m.count(t[i]))return -1;
vector <int>& v = m[t[i]];
vector <int> :: iterator it = upper_bound(v.begin(),
v.end(), pre);
if(it == v.end()){
ret++;
pre = v[0];
}else{
pre = *it;
}
}
return ret;
}
};
main(){
Solution ob;
cout << (ob.shortestWay("abc", "abcbc"));
}

### Input

"abc"
"abcbc"

## Output

2
Published on 13-Apr-2020 08:19:22