当前位置:网站首页>Leetcode- longest palindrome string - simple

Leetcode- longest palindrome string - simple

2022-06-13 05:49:00 AnWenRen

title :409 Longest palindrome - Simple

subject

Given a string of uppercase and lowercase letters , Find the longest palindrome string constructed from these letters .

In the process of construction , Please pay attention to case sensitivity . such as "Aa" Can't be treated as a palindrome string .

Be careful :
Suppose that the length of the string does not exceed 1010.

Example 1

 Input :
"abccccdd"

 Output :
7

 explain :
 The longest palindrome string we can construct is "dccaccd",  Its length is  7.

Code Java

//  Sort   Find two similarities  - 2ms
public int longestPalindrome(String s) {
    
    int result = 0;
    char[] chars = s.toCharArray();
    Arrays.sort(chars);
    for (int i = 1; i < chars.length; i++) {
    
        if (chars[i] == chars[i-1]) {
    
            i++;
            result += 2;
        }
    }
    if (result < chars.length)
        return result + 1;
    else return result;
}
//  Number of hash stores  -  Less memory usage   But it's still slow 
public int longestPalindrome1(String s) {
    
    int[] big = new int[26];
    int[] small = new int[26];
    int result = 0;
    for (int i = 0; i < s.length(); i++) {
    
        char ch = s.charAt(i);
        if (ch >= 'a') {
    
            small[ch - 97] ++;
        } else {
    
            big[ch - 65] ++;
        }
    }
    for (int i = 0; i < 26; i++) {
    
        result += big[i] / 2 * 2;
        result += small[i] / 2 * 2;
    }
    if (result < s.length())
        return result + 1;
    else return result;
}
//  Optimize array 
public int longestPalindrome2(String s) {
    
    int[] count = new int[128];
    int length = s.length();
    for (int i = 0; i < length; ++i) {
    
        char c = s.charAt(i);
        count[c]++;
    }
    int ans = 0;
    for (int v: count) {
    
        ans += v / 2 * 2;
    }
    if (ans < length)
        return ans + 1;
    return ans;
}
原网站

版权声明
本文为[AnWenRen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280507176117.html