

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print a closest string that does not contain adjacent duplicates in C++
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,
#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
- Related Questions & Answers
- Check that the String does not contain certain characters in Java
- Removing adjacent duplicates from a string in JavaScript
- Remove All Adjacent Duplicates In String in Python
- MySQL query to get a field value that does not contain empty spaces?
- Remove All Adjacent Duplicates in String II in C++
- Construct a PDA that accepts (a,b)* language but not contain bbbb?
- How to filter rows that contain a certain string in R?
- Print all the duplicates in the input string in C++
- Print all distinct permutations of a given string with duplicates in C++
- Java Regular Expression that doesn't contain a certain String.
- Find records in MongoDB that does NOT match a condition?
- How to extract elements of a list that do not contain NULL in R?
- How to split string values that contain special characters in R?
- Rearrange characters in a string such that no two adjacent are same in C++
- Adjacent elements of array whose sum is closest to 0 - JavaScript