【问题标题】:Make a given string as palindrome using java使用java将给定的字符串作为回文
【发布时间】:2015-01-21 10:59:44
【问题描述】:

谁能帮我解决以下问题

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

eg: input: ABC, output: ABCBA

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

在最好的情况下,如果我们也能达到以下结果就更好了

eg: input: AAB, output: ABA

对于第一个例子,我尝试了这种方法

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

【问题讨论】:

  • 为什么我们可以服用AAB并制造ABA?我们可以拿ABC做ABA吗?甚至是真正理想的 {'A','B','C'} 是三个单字符回文?
  • 您必须向我们展示解决问题的一些努力。 StackOverflow 不是一个“代码顺序”网站。 What have you tried?您认为有哪些可能的解决方案?您是否尝试过在其他任何地方寻找这个答案?
  • @Elliott Frisch:没有第二个是不同的例子。它与第一个无关。在第一个示例中,我们只是将字符串的一部分添加到原始字符串中(不删除现有字符)。在第二个中,我认为我们可以使用重复的单词(以最小化插入),而不是制作 AAB--> AABAA,我们可以更好地使用 ABA
  • 允许对输入字符串进行哪些转换?目前尚不清楚为什么 AAB 可以成为 ABA。
  • @Alex,我在堆栈溢出中搜索并尝试了this。但我无法理解建议的方法。我已经尝试在示例 1 中使用链表。无法执行示例 2

标签: java algorithm data-structures


【解决方案1】:

回答我自己的问题。 第二个例子

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 2015-06-10
    • 1970-01-01
    相关资源
    最近更新 更多