zoukankan      html  css  js  c++  java
  • [LeetCode] 1400. Construct K Palindrome Strings

    Given a string s and an integer k. You should construct k non-empty palindrome strings using all the characters in s.

    Return True if you can use all the characters in s to construct k palindrome strings or False otherwise.

    Example 1:

    Input: s = "annabelle", k = 2
    Output: true
    Explanation: You can construct two palindromes using all characters in s.
    Some possible constructions "anna" + "elble", "anbna" + "elle", "anellena" + "b"
    

    Example 2:

    Input: s = "leetcode", k = 3
    Output: false
    Explanation: It is impossible to construct 3 palindromes using all the characters of s.
    

    Example 3:

    Input: s = "true", k = 4
    Output: true
    Explanation: The only possible solution is to put each character in a separate string.
    

    Example 4:

    Input: s = "yzyzyzyzyzyzyzy", k = 2
    Output: true
    Explanation: Simply you can put all z's in one string and all y's in the other string. Both strings will be palindrome.
    

    Example 5:

    Input: s = "cr", k = 7
    Output: false
    Explanation: We don't have enough characters in s to construct 7 palindromes.

    Constraints:

    • 1 <= s.length <= 10^5
    • All characters in s are lower-case English letters.
    • 1 <= k <= 10^5

    构造 K 个回文字符串。

    给你一个字符串 s 和一个整数 k 。请你用 s 字符串中 所有字符 构造 k 个非空 回文串 。

    如果你可以用 s 中所有字符构造 k 个回文字符串,那么请你返回 True ,否则返回 False 。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/construct-k-palindrome-strings
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    思路是贪心。题意是试图把 input 字符串 s 分割,请你判断是否有可能把 input 字符串分割成 k 份,同时每份子串都是一个回文串。这里贪心的思想是,如果我可以把 s 分成 k 个回文串的话,那么出现次数为奇数的字母个数一定不能超过 k 个,否则就不行。出现次数为 3 次或者 5 次的字母的确可以自成一个回文,但是他不能再和其他出现次数为奇数的字母合并成另一个回文了,所以出现次数为奇数的字母有多少,就会产生多少个子串。如果这个数字大于 k,就不能满足题意。

    时间O(n)

    空间O(n)

    Java实现

     1 class Solution {
     2     public boolean canConstruct(String s, int k) {
     3         int odd = 0;
     4         int len = s.length();
     5         int[] count = new int[26];
     6         for (int i = 0; i < len; i++) {
     7             count[s.charAt(i) - 'a']++;
     8         }
     9         for (int j = 0; j < count.length; j++) {
    10             if (count[j] % 2 != 0) {
    11                 odd++;
    12             }
    13         }
    14         return k <= len && odd <= k;
    15     }
    16 }

    LeetCode 题目总结

  • 相关阅读:
    HTTP协议学习笔记
    linux对文件某列求和
    mongodb拆库分表脚本
    mongodb基础应用
    mongodb实现对某列求和SUM
    员工价值——如何体现自己价值,如何被自己的领导认可
    使用MySQLMTOP监控MySQL性能(二)
    使用MySQLMTOP监控MySQL性能(一)
    apache+tomcat实现session共享
    apache+tomcat负载均衡3种实现方式
  • 原文地址:https://www.cnblogs.com/cnoodle/p/14877139.html
Copyright © 2011-2022 走看看