Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Convert given string so that it holds only distinct characters in C++
In this tutorial, we will be discussing a program to convert given string so that it holds only distinct characters.
For this we will be provided with a string. Our task is to traverse through the string and replace all the recurring characters with any random characters that are not already present into the string.
Example
#include<bits/stdc++.h>
using namespace std;
//collecting the distinct characters
//in the string
int calculate_zero(int i, int occurrences[]){
while (i < 26) {
//if it is present only once
if (occurrences[i] == 0)
return i;
i++;
}
//if all are doubles or more
return -1;
}
//printing the modified string
string print_modified(string str) {
int n = str.length();
//if conversion
//not possible
if (n > 26)
return "-1";
string ch = str;
int i, occurrences[26] = {0};
//counting the occurrences
for (i = 0; i < n; i++)
occurrences[ch[i] - 'a']++;
int index = calculate_zero(0, occurrences);
for (i = 0; i < n; i++) {
//replacing the character
if (occurrences[ch[i] - 'a'] > 1) {
occurrences[ch[i] - 'a']--;
ch[i] = (char)('a' + index);
occurrences[index] = 1;
//moving to the next character
index = calculate_zero(index + 1, occurrences);
}
}
cout << ch << endl;
}
int main() {
string str = "tutorialspoint";
print_modified(str);
}
Output
bucdrealspoint
Advertisements