C++で文字の繰り返しを含むすべての順列を出力します
この問題では、n文字の文字列が与えられ、文字列の文字のすべての順列を出力する必要があります。文字列の文字の繰り返しは許可されています。順列の印刷は、アルファベット順(辞書式順序)で実行する必要があります。
トピックをよりよく理解するために例を見てみましょう:
入力- XY
出力- XX、XY、YX、YY
この問題を解決するには、修正と繰り返しのロジックを使用する必要があります。ここでは、配列の最初のインデックスで1つの要素を修正してから、シーケンス内の次の要素を再帰的に呼び出します。
ソリューションを明確にする実装例を見てみましょう。
文字列XYを入力します。
1つのインデックスで最初の要素を修正します:X _
他の要素を再帰的に呼び出して、次のように入力します:XX-> XY
次に、index1の次の要素を修正します:Y _
他の要素を再帰的に呼び出して入力します:YX-> YY
同じロジックを3,4、nの長さの文字列に使用できます。
例
#include <iostream>
#include<string.h>
using namespace std;
void printPermutations(char *str, char* permutations, int last, int index){
int i, len = strlen(str);
for ( i = 0; i < len; i++ ) {
permutations[index] = str[i] ;
if (index == last)
cout<<permutations <<"\t";
else
printPermutations (str, permutations, last, index+1);
}
}
int main() {
char str[] = "ABC";
cout<<"All permutations of the string with repetition of "<<str<<" are: "<<endl ;
int len = strlen(str) ;
char permutations[len];
printPermutations (str, permutations, len-1, 0);
return 0;
} 出力
All permutations of the string with repetition of ABC are:
AAA AAB AAC ABA ABB ABC ACA ACB ACC BAA BAB BAC BBA BBB BBC BCA BCB BCC CAA CAB CAC CBA CBB CBC CCA CCB CCC
-
C++で文字列内のすべての文字を切り替えます
このプログラムは、文字列の文字を大文字に変換します。ただし、このタスクは、c ++クラスライブラリのtoUpper()メソッドを使用して簡単に実行できます。しかし、このプログラムでは、大文字の文字のASCII値を計算することによってこれを実行します。アルゴリズムは次のとおりです。 アルゴリズム START Step-1: Declare the array of char Step-2: Check ASCII value of uppercase characters which must grater than A and lesser
-
Javaで文字列のすべての順列を出力します
以下は、文字列のすべての順列を出力するJavaプログラムです- 例 public class Demo{ static void print_permutations(String my_str,String my_ans){ if (my_str.length() == 0){ System.out.print(my_ans + " "); return;