Print a closest string that does not contain adjacent duplicates in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a string. Our task is to print a string that is closest to the current string and does not contain any adjacent duplicate characters.

Let’s take an example to understand the problem

Input: string = “good”
Output: goad

In this example, we found that the elements at index 1 and 2 are the same, so we change the elements at index 2.

To solve this problem, we will traverse the string and check if any two adjacent elements have are same. If yes, then change the second element (if i and i+1 elements are the same, change i+1 element). Solving this will use the greedy algorithm and for each adjacent pair of similar elements, we will make one change. One thing we have to keep in mind is checking all nearby elements while changing i.e. if we are changing ith element than after change i+1 and i index element should be different.

Example

Program to show the implementation of our solution,

Live Demo

#include <iostream>
#include <string.h>
using namespace std;
void printStringWithNoDuplicates(string str){
int len = str.length();
for (int i = 1; i < len; i++){
if (str[i] == str[i - 1]){
str[i] = 'a';
while (str[i] == str[i - 1] || (i + 1 < len && str[i] == str[i + 1])) str[i]++;
i++;
}
}
cout<<str;
}
int main(){
string str = "good";
cout<<"The orignal string is : "<<str<<endl;
cout<<"String without adjecent duplicate characters is : ";
printStringWithNoDuplicates(str);
return 0;
}

Output

The orignal string is : good
String without adjecent duplicate characters is : goad
Published on 27-Jan-2020 06:45:00