package com.gdh.backtext;import java.util.HashMap;import java.util.Map;import java.util.Map.Entry; public class BackText { String text; public BackTex ...
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;
}
}
//迴圈列印
for(Entry<Character,Integer> item:map.entrySet()){
System.out.println("字元:" + item.getKey() + " 值:" + 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("該字元串不能轉換為迴文字");
return null;
}
StringBuffer temp=new StringBuffer(text);//線程安全
//StringBuilder temp=new StringBuilder();//線程非安全
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("該字元串不是迴文字");
else
System.out.println("該字元串是迴文字");
String dest=new String();
System.out.println("開始轉換...");
dest=bt.convert( ) ;
System.out.print("轉換後的結果為:");
System.out.println(dest);
}
}