【问题标题】:Trying to find the longest palindrome for this input试图找到这个输入的最长回文
【发布时间】:2019-06-13 20:46:10
【问题描述】:

给定一个由小写或大写字母组成的字符串,找出可以用这些字母构建的最长回文的长度。

这是区分大小写的,例如“Aa”在这里不被视为回文。

注意:

假设给定字符串的长度不会超过 1,010。

例子:

输入:"abccccdd"

输出:7

解释:

可以构建的最长回文是“dccaccd”,长度为 7。

我的代码适用于简单的输入,例如 "abccccdd""banana",但不适用于 "civilwartestingwhetherthatnaptionoranynartionsoconceivedandsodedicatedcanlongendureWeareqmetonagreatbattlefiemldoftzhatwarWehavecometodedicpateaportionofthatfieldasafinalrestingplaceforthosewhoheregavetheirlivesthatthatnationmightliveItisaltogetherfangandproperthatweshoulddothisButinalargersensewecannotdedicatewecannotconsecratewecannothallowthisgroundThebravelmenlivinganddeadwhostruggledherehaveconsecrateditfaraboveourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorlongrememberwhatwesayherebutitcanneverforgetwhattheydidhereItisforusthelivingrathertobededicatedheretotheulnfinishedworkwhichtheywhofoughtherehavethusfarsonoblyadvancedItisratherforustobeherededicatedtothegreattdafskremainingbeforeusthatfromthesehonoreddeadwetakeincreaseddevotiontothatcauseforwhichtheygavethelastpfullmeasureofdevotionthatweherehighlyresolvethatthesedeadshallnothavediedinvainthatthisnationunsderGodshallhaveanewbirthoffreedomandthatgovernmentofthepeoplebythepeopleforthepeopleshallnotperishfromtheearth"。我不确定如何调试它。

class Solution {
    public int longestPalindrome(String s) {
        Map<Character, Integer> map = new HashMap<>();
        char[] carr = s.toCharArray();
        Arrays.sort(carr);
        int leftInd = 0;
        int rightInd = 0;
        for(int i=0; i<carr.length; i++){
            if(map.containsKey(carr[i]))
                continue;
            else
                map.put(carr[i], 1);
        }
        for(int i=0; i<carr.length-1; i++){
            for(int j=i+1; j<carr.length; j++){
                if(carr[i]==carr[j]){
                    if(map.get(carr[i])==null)
                        continue;
                    carr[j] = Character.MIN_VALUE;
                    int count = map.get(carr[i]);
                    map.put(carr[i], count + 1);
                }
            }
        }
        int ans = 0;
        int[] oddValArr = new int[map.size()];
        int oddInd = 0;
        for (Map.Entry<Character, Integer> entry : map.entrySet()) {
            Character key = entry.getKey();
            Integer value = entry.getValue();
            if(value % 2 == 0){
                ans += value;
            }
            else{
                oddValArr[oddInd] = value;
                oddInd++;
            }
        }
        int biggestOddNum = 0;
        for(int i=0; i<oddValArr.length; i++){
            if(oddValArr[i] > biggestOddNum)
                biggestOddNum = oddValArr[i];
        }
        return ans + biggestOddNum;
     }
}

输出 655

预期 983

【问题讨论】:

  • 您没有计算奇数的字母。如果您有 3 个“a”字母,则可以在回文中使用其中的 2 个,对吗?在所有奇数字母中,您可以在回文的中心使用剩余的一个。

标签: java palindrome


【解决方案1】:

您的错误在于,您只使用了oddValArr 中最大的 奇数组。例如,如果输入是“aaabbb”,最大的回文是“abbba”,所以组a的长度为3,是一个奇数,我们使用了3 - 1 = 2它的字母。

此外,那些嵌套的 for 循环可以用一个 for 替换,使用 Map:

public int longestPalindrome(String s) {
    Map<Character, Integer> map = new HashMap<>();  // letter groups
    for(int i=0; i<s.length(); i++){
        char c = s.charAt(i));
        if(map.containsKey(c))
            map.put(c, map.get(i) + 1);
        else
            map.put(c, 1);
    }

    boolean containsOddGroups = false;
    int ans = 0;
    for(int count : map.values()){
        if(count % 2 == 0)  // even group
            ans += count;
        else{  // odd group
            containsOddGroups = true;
            ans += count - 1;
        }
    }
    if(!containOddGroups)
        return ans;
    else
        return ans + 1;  // we can place one letter in the center of palindrome
}

【讨论】:

    【解决方案2】:

    你快到了,但有点过于复杂了。我的解决方案几乎只从您的解决方案中删除代码:

    public static int longestPalindrome(String s) {
        Map<Character, Integer> map = new HashMap<>();
        char[] carr = s.toCharArray();
        for (int i = 0; i < carr.length; i++) {
            if (map.containsKey(carr[i]))
                map.put(carr[i], map.get(carr[i]) + 1);
            else
                map.put(carr[i], 1);
        }
    
        int ans = 0;
        int odd = 0;
        for (Integer value : map.values()) {
            if (value % 2 == 0) {
                ans += value;
            } else {
                ans += value - 1;
                odd = 1;
            }
        }
        return ans + odd;
    }
    

    解释:

    • 第二个循环已与排序一起被删除 - 它已合并到第一个循环中。根本不需要排序。
    • 然后你迭代一个字符出现频率的计数
      • 如果连你都像以前一样增加ans
      • 如果它是奇数,你可以使用它的 count - 1 字符作为偶数长度的回文
    • 如果您发现至少一个奇数出现,您可以将单个奇数字符放入回文的中心,并将其长度增加一

    【讨论】:

      猜你喜欢
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 2019-11-06
      • 1970-01-01
      • 2015-05-04
      • 2018-09-09
      • 2020-05-04
      • 1970-01-01
      相关资源
      最近更新 更多