如果可能,在C++中重新排列字元以形成迴文


給定任意長度的字串“str”。任務是重新排列字元,使其成為迴文字串,無需新增或刪除輸入字串中的任何字元。迴文字串是指字元排列方式從頭到尾讀音相同的字串。

讓我們看看各種輸入輸出場景:

輸入 - 字串 str = "itnin"

輸出 - 如果可能,重新排列字元以形成迴文是:nitin

解釋 - 給定一個字串型別變數,例如str。現在我們將重新排列輸入字串的字元,使其成為迴文字串;如果不可能,則返回“不可能”。因此,給定輸入字串的輸出是“nitin”。

輸入 - 字串 str = "baaaba"

輸出 - 如果可能,重新排列字元以形成迴文是:aabbaa

解釋 - 給定一個字串型別變數,例如str。現在我們將重新排列輸入字串的字元,使其成為迴文字串;如果不可能,則返回“不可能”。因此,給定輸入字串的輸出是“aabbaa”。

下面程式中使用的方法如下:

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

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

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

    • 建立一個名為“um”的無序對映變數,它儲存字元和整數型別的鍵值對。

    • 宣告一個整數型別的變數為total,並將其設定為0。

    • 建立一個字元型別的變數為‘ch’,和字串型別的變數為str_1和str_2。

    • 從i=0開始迴圈,直到i小於length。在迴圈內,將um[str[i]]遞增1。

    • 開始迴圈遍歷對映‘um’。在迴圈內,檢查IF it.second % 2 不等於0,則將total加1,並將ch設定為it.first。

    • 檢查IF total大於1,或者total = 1且length % 2 = 0,則返回0。

    • 開始迴圈遍歷對映‘um’。在迴圈內,設定str(it.second / 2, it.first),str_1為str_1 + str,str_2為str + str_2。

    • 檢查IF total = 1,則返回str_1 + ch + str_2。否則,返回str_1 + str_2。

  • 列印結果。

示例

#include <bits/stdc++.h>
using namespace std;
string Rearrangement(string str, int length){
   unordered_map<char, int> um;
   int total = 0;
   char ch;
   string str_1 = "";
   string str_2 = "";

   for (int i = 0; i < length; i++){
      um[str[i]]++;
   }
   for(auto it : um){
      if(it.second % 2 != 0){
         total++;
         ch = it.first;
      }
   }
   if(total > 1 || total == 1 && length % 2 == 0){
      return 0;
   }
   for(auto it : um){
      string str(it.second / 2, it.first);
      str_1 = str_1 + str;
      str_2 = str + str_2;
   }
   if(total == 1){
      return str_1 + ch + str_2;
   }
   else{
      return str_1 + str_2;
   }
}
int main(){
   string str = "itnin";
   int length = str.size();
   cout<<"Rearrangement of characters to form palindrome if possible is: "<<Rearrangement(str, length);
   return 0;
}

輸出

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

Rearrangement of characters to form palindrome if possible is: nitin

更新於:2021年11月2日

889 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.