C/C++教程

leetcode_409. 最长回文串

本文主要是介绍leetcode_409. 最长回文串,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

给定一个包含大写字母和小写字母的字符串 s ,返回 通过这些字母构造成的 最长的回文串 。

在构造过程中,请注意 区分大小写 。比如 "Aa" 不能当做一个回文字符串。

 

示例 1:

输入:s = "abccccdd"
输出:7
解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。

int longestPalindrome(char * s){
    int len = strlen(s);

    int *hash = (int *)malloc(sizeof(int) * 100);
    memset(hash, 0, sizeof(int) * 100) ;
    int res = 0;
    for(int i = 0; i < len; i++) {
        // 一开始 用的 - ‘a’ 出现错误
        hash[s[i] - '0']++;
    }
    int flag = 0;
    int tmp = 0;
    for(int i = 0; i < 100; i++) {
        if(hash[i] % 2 == 0) {
            res += hash[i];
        } else {
            flag = 1;
            tmp = hash[i] / 2;
            res += tmp * 2 ;
        }
    }
    if(flag == 1) {
        res += 1;
    }

    return res;

}

 

上面自己写的。 看下标准答案

 

 1 int longestPalindrome(char * s){
 2     int slen = strlen(s);
 3     if(slen == 0) {
 4         return NULL;
 5     }
 6     if(slen == 1) {
 7         return 1;
 8     }
 9     int *hash = (int *)malloc(sizeof(int) * 128);
10     memset(hash, 0, sizeof(int) * 128);
11 
12     for(int i = 0; i < slen; i++) {
13         hash[s[i]]++;
14     }
15     int res = 0;
16     for(int i = 0; i < 128; i++) {
17         res += hash[i] - hash[i]%2; // 很精妙 ,这句话 
18     }
19     if(res < slen) {
20         return res + 1;
21     }else {
22         return res;
23     }
24 }

 

这篇关于leetcode_409. 最长回文串的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!