[英]How to rearrange string after permutation
我正在使用下面的代碼根據特定表置換字符串。
public static void main(String[] args) {
int[] IP = { 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7 };
String text = "00000001 00100011 01000101 01100111 10001001 10101011 11001101 11101111".replace(" ", "");
text = Permute(text,IP);
System.out.println(text);
}
public static String Permute(String text,int [] table )
{
String keys = "0" + text;
StringBuilder sb = new StringBuilder ();
for (int i = 1 ; i <= table.length; i++)
{
sb.append(keys.charAt(table[i-1]));
}
return sb.toString();
}
更新 :有創建另一個方法來恢復原始字符串的想法嗎? 就像是 :
public static String GetoriginalText(String TextafterPermutation,int [] table )
在語句中text = Permute(text,IP);
您正在分配從Permute
函數返回的String
對象的引用,因此保留了text
變量的原始引用將替換為Permute
函數返回的新引用。
如果要保留text
的原始引用,只需使用其他任何變量,例如String output = Permute(text,IP);
。
您可以使用如下所述的簡單程序:
public static String dePermute(String text, int[] table){
String keys = text;
System.out.println(table.length);
String[] str = new String[table.length];
for (int i = 1; i <= table.length; i++) {
System.out.println("Coming "+table[i - 1]);
str[table[i - 1]-1] = ""+keys.charAt(i-1);
//sb.append(keys.charAt(table[i - 1]));
}
return Arrays.toString(str).replace("[", "").replace("]", "").replace(",", "").replace(" ", "");
}
您可以使用此程序中說明的概念。 我只是逆轉了您在Permute
函數中所做的過程。
您可以使用根據表映射填充的字符數組
public static String RePermute(final String text, final int[] table) {
final String keys = text;
char[] chararray = new char[table.length];
for (int i = 0; i < keys.length() && i < table.length; i++) {
chararray[table[i]-1] = keys.charAt(i);
}
return new String(chararray);
}
此代碼遍歷您的文本,並在表中指定的chararray位置寫入當前迭代的char。
注意:您的代碼中有一些問題我沒有解決。 例如,我真的不明白為什么您總是在文本前面加上“ 0”。 另外,您可能想處理傳遞的文本和表格的長度不同的情況。
編輯:我刪除了在傳遞的文本前面添加“ 0”的部分,而是更改了循環以從i = 0開始而不是i = 1。
您可以簡化算法以使用字符數組而不是StringBuilder
:
public static String permute(String text,int [] table )
{
char[] chars = new char[table.length];
for (int i = 0 ; i < table.length; i++) {
chars[i] = text.charAt(table[i]-1);
}
return new String(chars);
}
之后,反向算法更為明顯。 您只需要進行反向分配:
public static String undo(String text,int [] table ) {
char[] chars = new char[table.length];
for (int i = 0; i < table.length; i++)
{
chars[table[i]-1] = text.charAt(i);
}
return new String(chars);
}
假設您的排列表不變,則可以執行以下操作:
public static String GetoriginalText(String TextafterPermutation,int [] table ){
char[] chars=new char[table.length];
for(int i=0;i<table.length;i++){
chars[table[i] - 1] = TextafterPermutation.charAt(i);
}
return new String(chars);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.