Back-to-text algorithm (java version), text algorithm java version
Package com. gdh. backtext;
Import java. util. HashMap;
Import java. util. Map;
Import java. util. Map. Entry;
Public class BackText {
String text;
Public BackText (){
Super ();
This. text = null;
}
Public BackText (String text ){
Super ();
This. text = text;
}
Public boolean isBackText (){
For (int I = 0, j = text. length ()-i-1; I <= j; I ++, j --){
If (text. charAt (I )! = Text. charAt (j )){
Return false;
}
}
Return true;
}
Public Map <Character, Integer> countString (){
Map <Character, Integer> map = new HashMap <> ();
Int count = 0;
String temp = new String ();
For (int I = 0; I <text. length (); I ++ ){
If (temp. indexOf (text. charAt (I), 0) <0 ){
Temp + = text. charAt (I );
}
}
Map. clear ();
For (int I = 0; I <temp. length (); I ++ ){
If (! Map. containsKey (temp. charAt (I ))){
For (int j = 0; j <text. length (); j ++ ){
If (text. charAt (j) = temp. charAt (I )){
Count ++;
}
}
Map. put (temp. charAt (I), count );
Count = 0;
}
}
// Print cyclically
For (Entry <Character, Integer> item: map. entrySet ()){
System. out. println ("character:" + item. getKey () + "value:" + item. getValue ());
}
Return map;
}
Public String convert (){
Int checksum = 0;
Int itemcount = 0;
Map <Character, Integer> map = countString ();
For (Entry <Character, Integer> item: map. entrySet ()){
Checksum + = item. getValue ();
If (item. getValue () % 2! = 0)
Itemcount ++;
}
If (itemcount> 1 ){
System. out. println ("this string cannot be converted back to text ");
Return null;
}
StringBuffer temp = new StringBuffer (text); // thread security
// StringBuilder temp = new StringBuilder (); // The thread is not safe.
Int begIdx = 0;
Int endIdx = checksum-1;
Character key = null;
Boolean flag = false;
For (Entry <Character, Integer> item: map. entrySet ()){
If (checksum % 2 = 0 ){
For (int I = 0; I <item. getValue ()/2; I ++ ){
Temp. setCharAt (begIdx ++, item. getKey ());
Temp. setCharAt (endIdx --, item. getKey ());
}
} Else {
If (item. getValue () % 2 = 0 ){
For (int I = 0; I <item. getValue ()/2; I ++ ){
Temp. setCharAt (begIdx ++, item. getKey ());
Temp. setCharAt (endIdx --, item. getKey ());
}
} Else {
Key = item. getKey ();
Flag = true;
Continue;
}
}
}
If (flag)
{
For (int I = 0; I <map. get (key); I ++ ){
Temp. setCharAt (begIdx ++, key );
}
}
Return temp. toString ();
}
Public static void main (String [] args ){
BackText bt = new BackText ("1122334455667788990 ");
If (! Bt. isBackText ())
System. out. println ("this string is not a back-to-text ");
Else
System. out. println ("this string is a back-to-text ");
String dest = new String ();
System. out. println ("START conversion ...");
Dest = bt. convert ();
System. out. print ("the converted result is :");
System. out. println (dest );
}
}