轉換給定字串,使其僅包含 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

更新日期: 16-01-2020

190 瀏覽

啟動你的 職業

完成課程以獲得認證

開始
廣告
© . All rights reserved.