Construct K Palindrome Strings

本文介绍了一种算法,用于判断是否能利用给定字符串中的所有字符构建k个回文串。通过统计字符串中各字符出现次数的奇偶性来确定可能性,并提供了具体的实现代码。

Given a string s and an integer k, 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.

思路:统计oddnum,k个palindrome,奇数的char不能超过k,同时k不能大于str.length();

class Solution {
    public boolean canConstruct(String s, int k) {
        int[] count = new int[26];
        for(int i = 0; i < s.length(); i++) {
            count[s.charAt(i) - 'a']++;
        }
        int oddnum = 0;
        for(int i = 0; i < count.length; i++) {
            if(count[i] % 2 != 0) {
                oddnum++;
            }
        }
        return oddnum <= k && k <= s.length();
    }
}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值