使用java将给定的字符串作为回文使用

问题描述:

任何人都可以请我帮助解决以下问题使用java将给定的字符串作为回文使用

检查字符串是否是回文。如果字符串不是回文,则将其设为回文。

eg: input: ABC, output: ABCBA 

我知道如何检查字符串是否是回文。请在问题的第二部分提供帮助。

在最好的情况下,更好,如果我们能够达到以下效果也

eg: input: AAB, output: ABA 

为1〔实施例我想这种做法

LinkedList <String> q = new LinkedList<>(); 
    //String [] ar ={"a","b","c","b","d"}; 
    String [] ar ={"A","B","C"};; 
    int mid=ar.length/2; 

    q.addFirst(ar[mid]); 
    for(int i= mid, j=mid; i>=0&&j<ar.length;){ 
     if(j+1==ar.length && i-1==-1) 
      break; 
     q.addFirst(ar[i-1]); 
     if(ar[i-1]!=ar[j+1]){ 
      q.addLast(ar[i-1]); 
      q.addLast(ar[j+1]); 
      q.addFirst(ar[j+1]); 

     }else{ 
      q.addLast(ar[j+1]); 
     } 
     j++; 
     i--; 
    } 
+4

为什么我们可以采取AAB和使ABA?我们可以参加ABC并制作ABA吗?或者甚至是真正理想的{'A','B','C'},这是三个一个字符的回文? – 2014-11-23 18:52:04

+0

你必须向我们展示解决问题的一些努力。 StackOverflow不是'代码顺序'网站。 [你有什么尝试](http://www.whathaveyoutried.com)?你认为有什么可能的解决方案?你有没有尝试在其他地方寻找这个答案? – 2014-11-23 18:54:15

+0

@Elliott Frisch:没有第二个例子。它与第一个无关。在第一个例子中,我们只是将字符串的一部分添加到原始字符(不删除现有的字符)。在第二种情况下,我认为我们可以利用重复的单词(做最小的插入),而不是制作AAB - > AABAA,我们可以做得更好ABA – Babulu 2014-11-23 18:56:16

回答我的问题。 对于第二个例子

public static boolean makePal(String input){ 

    HashMap<Character, Integer> map = new HashMap<>(); 
    int value =1, numberOfOddOccurence = 0; 
    //find the number of occurrences 
    for(int i=0; i<input.length(); i++){ 
     char key = input.charAt(i); 
     if(!map.containsKey(key)){ 
      map.put(key, value); 
     }else{ 
      map.put(key, map.get(key)+1); 
     } 
    } 

    //find the number of char with odd counts 
    for(Map.Entry<Character, Integer> a : map.entrySet()){ 
     if(a.getValue()%2==1){ 
      numberOfOddOccurence++; 
     } 
    } 

    if(numberOfOddOccurence>1) 
     return false; 
    else{ 
     char [] charArray = new char[input.length()]; 
     int cursor = 0; 
     for(Map.Entry<Character, Integer> a : map.entrySet()){ 
      if(a.getValue()%2==0){ 
       charArray[cursor] = (char)(a.getKey()); 
       charArray[input.length()-cursor-1] = (char)(a.getKey()); 
       cursor++; 
      }else{ 
       charArray[(int) Math.ceil(input.length()/2)] = (char) (a.getKey()); 
      } 
     } 
     System.out.println(String.valueOf(charArray)); 
    } 

    return true; 
}