在本教程中,我们将讨论一个程序来转换给定的字符串,以便它仅包含不同的字符。
为此,我们将提供一个字符串。我们的任务是遍历字符串,并用字符串中不存在的任何随机字符替换所有重复出现的字符。
#include<bits/stdc++.h>
using namespace std;
//收集不同的字符
//在字符串中
int calculate_zero(int i, int occurrences[]){
while (i < 26) {
//如果仅存在一次
if (occurrences[i] == 0)
return i;
i++;
}
//如果所有都是双倍或更多
return -1;
}
//打印修改后的字符串
string print_modified(string str) {
int n = str.length();
//如果转换
//不可能
if (n > 26)
return "-1";
string ch = str;
int i, occurrences[26] = {0};
//计算出现次数
for (i = 0; i < n; i++)
occurrences[ch[i] - 'a']++;
int index = calculate_zero(0, occurrences);
for (i = 0; i < n; i++) {
//替换字符
if (occurrences[ch[i] - 'a'] > 1) {
occurrences[ch[i] - 'a']--;
ch[i] = (char)('a' + index);
occurrences[index] = 1;
//移至下一个字符
index = calculate_zero(index + 1, occurrences);
}
}
cout << ch << endl;
}
int main() {
string str = "nhooo";
print_modified(str);
}输出结果
bucdrealspoint