Check if a String can be converted to another by inserting character same as both neighbours
Last Updated :
21 Oct, 2022
Given 2 strings A and B . The task is to check if A can be converted into B by performing the following operation any number of times :
- Choose an index from 0 to N - 2 (suppose N is the length of A). If the character at ith index is equal to the character at (i + 1 )th index, then insert the same character between the ith and (i + 1)th index.
Examples:
Input: A = "abbaac", B = "abbbbaaac"
Output: YES
Explanation: A can be converted into B by performing the operations as follows:
- Insert b between 2nd and 3rd characters of A. ( A becomes abbbaac )
- Insert b between 2nd and 3rd characters of A.( A becomes abbbbaac )
- Insert a between 6th and 7th characters of A. ( A becomes abbbbaaac )
Input: A = "xyzz", B = "xyyzz"
Output: NO
Approach: The given problem can be solved by applying the concept of Run Length Encoding on given strings. For example, strings in 1st example can be encoded as follows :
A = {(a, 1), (b, 2), (a, 2), (c, 1)}
B = {(a, 1), (b, 4), (a, 3), (c, 1)}
Let's generalize the encoding of 2 strings as :
A = {(a1, x1), (a2, x2), (a3, x3).....(aN, xN)}
B = {(b1, y1), (b2, y2), (b3, y3)....(bM, yM)}
Now, A can be made equal to B, if the following 3 conditions are satisfied:
- N = M
- ai = bi, for i = 1, 2, 3....N
- Either (xi = yi ) or (xi < yi and xi ? 2) for i = 1, 2, 3....N
So, the problem can be solved easily by following the below steps:
- Apply Run Length Encoding on both strings.
- Check if the encodings of the strings satisfy above mentioned 3 conditions.
Below is the implementation for the above approach:
C++
// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to perform Run Length Encoding
// on a string S and store that
// in a vector V
void runLengthEncoding(string S, vector<pair<char, int> >& V)
{
int count = 1;
for (int i = 1; i < S.length(); i++) {
if (S[i] != S[i - 1]) {
V.push_back({ S[i - 1], count });
count = 0;
}
count++;
}
V.push_back({ S.back(), count });
}
// Function to Check if a string can be
// converted into another by performing
// the given operation any number of times
bool isPossible(string A, string B)
{
// Declaring vectors V1 and V2 to store
// Run Length Encoding of Strings A and B
vector<pair<char, int> > V1, V2;
runLengthEncoding(A, V1);
runLengthEncoding(B, V2);
// Checking for 1st condition
if (V1.size() != V2.size()) {
return false;
}
for (int i = 0; i < V1.size(); i++) {
// Checking for second condition
if (V1[i].first != V2[i].first) {
return false;
}
// Checking for third condition
if (!(V1[i].second == V2[i].second || (V1[i].second < V2[i].second && V1[i].second >= 2))) {
return false;
}
}
// If all three conditions are
// satisfied, return true
return true;
}
// Driver Code
int main()
{
string A = "abbaac";
string B = "abbbbaaac";
// Function Call
bool answer = isPossible(A, B);
if (answer == 1) {
cout << "YES" << endl;
}
else {
cout << "NO" << endl;
}
}
Java
// Java code for the above approach
import java.util.*;
public class GFG
{
// Function to perform Run Length Encoding
// on a string S and store that
// in a vector V
static void runLengthEncoding(
String S, ArrayList<pair<Character, Integer> > V)
{
int count = 1;
for (int i = 1; i < S.length(); i++) {
if (S.charAt(i) != S.charAt(i - 1)) {
V.add(new pair<Character, Integer>(
S.charAt(i - 1), count));
count = 0;
}
count++;
}
V.add(new pair<Character, Integer>(
S.charAt(S.length() - 1), count));
}
// Function to Check if a string can be
// converted into another by performing
// the given operation any number of times
static boolean isPossible(String A, String B)
{
// Declaring vectors V1 and V2 to store
// Run Length Encoding of Strings A and B
ArrayList<pair<Character, Integer> > V1
= new ArrayList<pair<Character, Integer> >();
ArrayList<pair<Character, Integer> > V2
= new ArrayList<pair<Character, Integer> >();
runLengthEncoding(A, V1);
runLengthEncoding(B, V2);
// Checking for 1st condition
if (V1.size() != V2.size()) {
return false;
}
for (int i = 0; i < V1.size(); i++) {
// Checking for second condition
if (V1.get(i).first != V2.get(i).first) {
return false;
}
// Checking for third condition
if (!(V1.get(i).second == V2.get(i).second
|| (V1.get(i).second < V2.get(i).second
&& V1.get(i).second >= 2))) {
return false;
}
}
// If all three conditions are satisfied, return
// true
return true;
}
// Driver Code
public static void main(String[] args)
{
String A = "abbaac";
String B = "abbbbaaac";
// Function Call
boolean answer = isPossible(A, B);
if (answer == true) {
System.out.println("YES");
}
else {
System.out.println("NO");
}
}
}
// Pair Class
class pair<T, U> {
T first;
U second;
public pair(T first, U second)
{
this.first = first;
this.second = second;
}
}
// This code is contributed by Tapesh(tapeshdua420)
Python3
# Python code for the above approach
# Function to perform Run Length Encoding
# on a string S and store that
# in a vector V
def runLengthEncoding(S, V):
count = 1
for i in range(1, len(S)):
if S[i] != S[i - 1]:
V.append((S[i - 1], count))
count = 0
count += 1
V.append((S[-1], count))
# Function to Check if a string can be
# converted into another by performing
# the given operation any number of times
def isPossible(A, B):
# Declaring vectors V1 and V2 to store
# Run Length Encoding of Strings A and B
V1 = []
V2 = []
runLengthEncoding(A, V1)
runLengthEncoding(B, V2)
# Checking for 1st condition
if len(V1) != len(V2):
return False
for i in range(len(V1)):
# Checking for second condition
if V1[i][0] != V2[i][0]:
return False
# Checking for third condition
if not (V1[i][1] == V2[i][1] or (V1[i][1] < V2[i][1] and V1[i][1] >= 2)):
return False
# If all three conditions are satisfied, return true
return True
# Driver Code
if __name__ == '__main__':
A = "abbaac"
B = "abbbbaaac"
answer = isPossible(A, B)
print("YES") if answer else print("NO")
# This code is contributed by Tapesh(tapeshdua420)
C#
// C# implementation
using System;
using System.Collections.Generic;
// represent pair
public class Pair<T, U> {
public Pair() {
}
public Pair(T first, U second) {
this.First = first;
this.Second = second;
}
public T First { get; set; }
public U Second { get; set; }
};
public class GFG{
// Function to perform Run Length Encoding
// on a string S and store that
// in a vector V
public static void runLengthEncoding(string S, List<Pair<char, int>> V)
{
// Pair<String, int> pair = new Pair<String, int>("test", 2);
int count = 1;
for (int i = 1; i < S.Length; i++) {
if (S[i] != S[i - 1]) {
Pair<char, int> pair = new Pair<char, int>(S[i - 1], count);
V.Add(pair);
count = 0;
}
count++;
}
Pair<char, int> pair2 = new Pair<char, int>(S[S.Length -1], count);
V.Add(pair2);
}
// Function to Check if a string can be
// converted into another by performing
// the given operation any number of times
public static bool isPossible(string A, string B)
{
// Declaring vectors V1 and V2 to store
// Run Length Encoding of Strings A and B
//vector<pair<char, int> > V1, V2;
var V1 = new List<Pair<char, int>>();
var V2 = new List<Pair<char, int>>();
runLengthEncoding(A, V1);
runLengthEncoding(B, V2);
// Checking for 1st condition
if (V1.Count != V2.Count) {
return false;
}
for (int i = 0; i < V1.Count; i++) {
// Checking for second condition
if (V1[i].First != V2[i].First) {
return false;
}
// Checking for third condition
if (!(V1[i].Second == V2[i].Second || (V1[i].Second < V2[i].Second && V1[i].Second >= 2))) {
return false;
}
}
// If all three conditions are
// satisfied, return true
return true;
}
static public void Main (){
// Code
string A = "abbaac";
string B = "abbbbaaac";
// Function Call
bool answer = isPossible(A, B);
if (answer == true) {
Console.WriteLine("YES");
}
else {
Console.WriteLine("NO");
}
}
}
// this code is contributed by ksam24000
JavaScript
// Javascript code for the above approach
// Function to perform Run Length Encoding
// on a string S and store that
// in a vector V
function runLengthEncoding(S, V)
{
let count = 1;
for (let i = 1; i < S.length; i++) {
if (S[i] != S[i - 1]) {
V.push({ "first":S[i - 1],
"second":count });
count = 0;
}
count++;
}
V.push({ "first":S[S.length-1],
"second":count });
}
// Function to Check if a string can be
// converted into another by performing
// the given operation any number of times
function isPossible( A, B)
{
// Declaring vectors V1 and V2 to store
// Run Length Encoding of Strings A and B
let V1 = [];
let V2 = [];
runLengthEncoding(A, V1);
runLengthEncoding(B, V2);
// Checking for 1st condition
if (V1.length != V2.length) {
return false;
}
for (let i = 0; i < V1.length; i++) {
// Checking for second condition
if (V1[i].first != V2[i].first) {
return false;
}
// Checking for third condition
if (!(V1[i].second == V2[i].second || (V1[i].second < V2[i].second && V1[i].second >= 2))) {
return false;
}
}
// If all three conditions are
// satisfied, return true
return true;
}
// Driver Code
let A = "abbaac";
let B = "abbbbaaac";
// Function Call
let answer = isPossible(A, B);
if (answer == 1) {
console.log("YES");
}
else {
console.log("NO");
}
// This code is contributed by akashish__
Time Complexity: O(M + N), where M and N are lengths of string A and B respectively
Auxiliary Space: O(N)
Similar Reads
Check if string S can be converted to T by incrementing characters Given strings S and T. The task is to check if S can be converted to T by performing at most K operations. For the ith operation, select any character in S which has not been selected before, and increment the chosen character i times (i.e., replacing it with the letter i times ahead in the alphabet
8 min read
Check if a string can be converted to another by swapping of adjacent characters of given type Given two strings str1 and str2 of size N consisting of only three characters A, B, and C, the task is to check whether the string str1 can be changed to str2 using the below operations: Replacing one occurrence of âBCâ with âCBâ i.e swap adjacent âBâ and âCâ.Replacing one occurrence of âCAâ with âA
7 min read
Check if a given string can be converted to another by given possible swaps Given two strings str1 and str2, the task is to check if a string str1 can be converted to string str2 by performing the following operations any number of times: Swap any two characters of str1.Swap all the occurrences of a character of str1 to all occurrences of any other distinct character of str
8 min read
Check if one string can be converted to another Given two strings str and str1, the task is to check whether one string can be converted to other by using the following operation: Convert all the presence of a character by a different character. For example, if str = "abacd" and operation is to change character 'a' to 'k', then the resultant str
8 min read
Check if String can be generated by concatenating character or String itself Given a target string S consisting of lowercase alphabets, the task is to make this string by performing some operation on an empty string such that: The first operation is to append a lower case alphabet to string S and The second operation is to append a copy of S to itself. Note: The first operat
6 min read