zoukankan      html  css  js  c++  java
  • Lintcode627

    Description

    Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.

    This is case sensitive, for example "Aa" is not considered a palindrome here.

    Assume the length of given string will not exceed 1010.

    Example

    Given s = "abccccdd" return 7

    One longest palindrome that can be built is "dccaccd", whose length is 7.

    算法:

    问题转化为:计算字母匹配对数*2,若存在落单字母额外+1。(或者也可以转化为:总字符串长度-落单字母数,若存在落单字母额外+1)

    实现用set。

    细节:

    1. 注意每次成对后计数器是+=2, 而不是++ (当然为那一点效率也可以++最后再*=2)

    2. 注意回文串中间可以插一个字符这个特性。

    自己实现:

    public class Solution {
        /**
         * @param s: a string which consists of lowercase or uppercase letters
         * @return: the length of the longest palindromes that can be built
         */
        public int longestPalindrome(String s) {
            // write your code here
            
            int cnt = 0;
            if (s == null) {
                return cnt;
            }
            
            Set<Character> set = new HashSet<>();
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (set.contains(c)) {
                    // not only plus 1
                    cnt += 2;
                    set.remove(c);
                } else {
                    set.add(c);
                }
            }
            
            // !! you can insert one in the middle
            if (set.size() > 0) {
                cnt++;
            }
            return cnt;
        }
    }

    九章实现

    public class Solution {
        /**
         * @param s a string which consists of lowercase or uppercase letters
         * @return the length of the longest palindromes that can be built
         */
        public int longestPalindrome(String s) {
            // Write your code here
            Set<Character> set = new HashSet<>();
            for (char c : s.toCharArray()) {
                if (set.contains(c)) set.remove(c);
                else set.add(c);
            }
    
            int remove = set.size();
            if (remove > 0)
                remove -= 1;
            return s.length() - remove;
        }
    }
  • 相关阅读:
    python 多进程下的日志打印
    卷积神经网络思考点,卷积网络就是很多个小分类器构建的网络
    ShuffleNetV1 paper reading
    find,grep,mv 组合使用,对大量数据切割方便
    常用的开源协议
    python3 日志重复打印logger
    pytorch clamp 与clamp_区别
    version GLIBCXX_3.4.21 not defined in file libstdc++.so.6 with link time reference
    pytorch,cuda8,torch.cuda.is_available return flase (ubuntu14)
    opencv remap 函数
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9417197.html
Copyright © 2011-2022 走看看