在 C++ 中重新排列字串中的字元,使得沒有兩個相同的字元相鄰


給定一個字串,例如 str,其長度任意。任務是重新排列給定的字串,使其結果字串中沒有兩個相同的字元相鄰。

讓我們看看這個的各種輸入輸出場景 -

輸入 - 字串 str = "itinn"

輸出 - 使得沒有兩個相同的字元相鄰的字串字元的重新排列是:initn。

解釋 - 給定一個字串型別的變數,例如 str。現在,我們將以這樣的方式重新排列輸入字串的字元,即沒有兩個相同的字元出現在相同的位置,即移動 'nn',因為它們是相同的並且彼此相鄰。因此,最終字串將是 'initn'。

輸入 - 字串 str = "abbaabbaa"

輸出 - 使得沒有兩個相同的字元相鄰的字串字元的重新排列是:ababababa

解釋 - 給定一個字串型別的變數,例如 str。現在,我們將以這樣的方式重新排列輸入字串的字元,即沒有兩個相同的字元出現在相同的位置,即移動 'bb'、'aa'、'bb'、'aa',因為它們是相同的並且彼此相鄰。因此,最終字串將是 'ababababa'。

下面程式中使用的方案如下

  • 輸入一個字串型別的變數,例如 str,並計算字串的大小並將其儲存在一個名為 length 的變數中。

  • 檢查 IF length 為 0 則返回。

  • 將資料傳遞給函式 Rearrangement(str, length)。

  • 在函式 Rearrangement(arr, length) 內部

    • 將字串的大小設定為 (length + 1)/2。

    • 宣告一個向量型別的變數為 vec(26, 0),它將儲存整數型別的資料,以及一個字串型別的指標為 ptr(length, ‘ ‘)。一個整數型別的臨時變數為 0。

    • 開始迴圈 FOR 以迭代 str 透過它。在迴圈內部,設定 vec[it - ‘a’]++。

    • 建立一個字元型別的變數為 ch 並將其設定為對 maximum(vec) 函式的呼叫。

    • 宣告一個整數型別的變數為 total 並將其設定為 vec[ch - ‘a’]。

    • 檢查 IF total 大於 size 則返回。

    • 開始迴圈 WHILE total 然後將 ptr[temp] 設定為 ch,將 temp 設定為 temp + 2 並將 total 減 1。

    • 將 vec[ch - 'a'] 設定為 0。開始迴圈 FOR 從 i 為 0 到 i 小於 26。在迴圈內部,開始 while vec[i] 大於 0。將 temp 設定為 (temp >= length) ? 1 : temp 並將 ptr[temp] 設定為 'a' + i 以及 temp 設定為 temp + 2 並將 vec[i] 減 1。

    • 返回 ptr

  • 在函式 char maximum(const vector<int>& vec) 內部

    • 宣告一個整數型別的變數為 high 為 0 以及字元型別的變數為 'c'

    • 開始迴圈 FOR 從 i 為 0 到 i 小於 26。在迴圈內部,檢查 IF vec[i] 是否小於 high,然後將 high 設定為 vec[i] 並將 c 設定為 'a' + i。

    • 返回 c

  • 列印結果。

示例

#include <bits/stdc++.h>
using namespace std;
char maximum(const vector<int>& vec){
   int high = 0;
   char c;
   for(int i = 0; i < 26; i++){
      if(vec[i] > high){
         high = vec[i];
         c = 'a' + i;
      }
   }
   return c;
}
string Rearrangement(string str, int length){
   int size = (length + 1) / 2;
   vector<int> vec(26, 0);
   string ptr(length, ' ');
   int temp = 0;
   for(auto it : str){
      vec[it - 'a']++;
   }
   char ch = maximum(vec);
   int total = vec[ch - 'a'];
   if(total > size){
      return "";
   }
   while(total){
      ptr[temp] = ch;
      temp = temp + 2;
      total--;
   }
   vec[ch - 'a'] = 0;
   for(int i = 0; i < 26; i++){
      while (vec[i] > 0){
         temp = (temp >= length) ? 1 : temp;
         ptr[temp] = 'a' + i;
         temp = temp + 2;
         vec[i]--;
      }
   }
   return ptr;
}
int main(){
   string str = "itinn";
   int length = str.length();
   if(length == 0){
      cout<<"Please enter a valid string";
   }
   string count = Rearrangement(str, length);
   if(count == ""){
      cout<<"Please enter a valid string";
   }
   else{
      cout<<"Rearrangement of characters in a string such that no two adjacent are same is: "<<count;
   }
   return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出

Rearrangement of characters in a string such that no two adjacent are same is: initn

更新於: 2021年11月3日

864 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告