你的位置:首页 > Java教程

[Java教程]回文字算法(java版本)


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);
  }
}