转换给定字符串,使其仅包含 C++ 中的不同字符
在本教程中,我们将讨论一项程序,该程序将转换给定字符串,使其仅包含不同字符。
为此,我们将提供一个字符串。我们的任务是遍历整个字符串,并将所有重复出现的字符替换为尚未出现在字符串中的任何随机字符。
示例
#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); }
输出
bucdrealspoint
广告