C ++
 Computer >> コンピューター >  >> プログラミング >> C ++

C++で回文順列を作成するための最小限の削除


問題の説明

文字列Sが与えられた場合、文字列Sの順列を回文にするために削除できる最小文字を見つける必要があります

str =“ abcdba”の場合、1文字に削除されます。つまり、「c」または「d」のいずれかです。

アルゴリズム

1. There can be two types of a palindrome, even length, and odd length palindromes
2. We can deduce the fact that an even length palindrome must have every character occurring even number of times
3.An odd palindrome must have every character occurring even number of times except one character occurring odd number of time
4. Check the frequency of every character and those characters occurring odd number of times are then counted. Then the result is total count of odd frequency characters’ minus 1

#include <bits/stdc++.h>
#define MAX 26
using namespace std;
int minCharactersRemoved(string str) {
   int hash[MAX] = {0};
   for (int i = 0; str[i]; ++i) {
      hash[str[i] - 'a']++;
   }
   int cnt = 0;
   for (int i = 0; i < MAX; ++i) {
      if (hash[i] & 1) {
         ++cnt;
      }
   }
   return (cnt == 0) ? 0 : (cnt - 1);
}
int main(){
   string str = "abcdba";
   cout << "Minimum characters to be removed = " <<
   minCharactersRemoved(str) << endl;
   return 0;
}

上記のプログラムをコンパイルして実行する場合。次の出力を生成します

出力

Minimum characters to be removed = 1

  1. C++での回文の削除

    arrという整数配列があるとします。これで、1回の移動で、インデックスiからjまでの回文サブ配列を選択できます。ここでi <=jであり、指定された配列からそのサブ配列を削除します。サブアレイを削除した後、そのサブアレイの左側と右側の要素が移動して、削除によって残されたギャップを埋めることを覚えておく必要があります。配列からすべての数字を削除するために必要な最小移動数を見つける必要があります。 したがって、入力がarr =[1,3,4,1,5]の場合、出力は3になります。このシーケンスで削除できるため、[4]を削除してから、[1,3,1]を削除します。 [5]を削除します。 これを解決するに

  2. C++でのジョブスケジュールの最小難易度

    タスクのリストをd日でスケジュールするとします。タスクは依存しているため、i番目のタスクで作業するには、すべてのタスクjを完了する必要があります。ここで0 <=j