第一个值得思考

本文介绍了三个算法问题的解决方案:计算回文串个数、分割平衡字符串以及最少操作使数组递增。对于回文串问题,通过统计字符出现次数确定边界条件;平衡字符串问题中,计算连续相同字符段的个数;数组递增问题使用单遍历更新并计算最小操作数。这些算法展示了在字符串处理和数组操作中的效率和逻辑思维。
摘要由CSDN通过智能技术生成

csdn
找出可行的回文串个数

class Solution {
public:
    bool canConstruct(string s, int k) {
        // 右边界为字符串的长度
        int right = s.size();
        // 统计每个字符出现的次数
        int occ[26] = {0};
        for (char ch: s) {
            ++occ[ch - 'a'];
        }
        // 左边界为出现奇数次字符的个数
        int left = 0;
        for (int i = 0; i < 26; ++i) {
            if (occ[i] % 2 == 1) {
                ++left;
            }
        }
        // 注意没有出现奇数次的字符的特殊情况
        left = max(left, 1);
        return left <= k && k <= right;
    }
};

上面有点罗嗦
class Solution {
public:
    bool canConstruct(string s, int k) {
        int hash[26];
        int n = s.length();
        memset(hash, 0, sizeof(hash));
        for(int i = 0; i < n; i++) {
            hash[s[i] - 'a']++; //(1)
        }

        int cnt = 0;
        for(int i = 0; i < 26; i++) {
            if (hash[i] & 1) //(2)
                cnt++;
        }
        if(k < cnt || k > n) //(3)
            return false;
        return true;
    }
};

分割平衡字符串

class Solution {
public:
    int balancedStringSplit(string s) {
         int cnt=0;int size=s.length();int res=0;
         for(int i=0;i<size;i++){
             if(s[i]=='L'){
                 cnt++;
             }else if(s[i]=='R'){
                 cnt--;
             }
             if(!cnt){
                 res++;
             }
         }
         return res;
    }
};

最少操作使数组递增

class Solution {
public:
    int minOperations(vector<int>& nums) {
        int n=nums.size();int res=0;
        if(n==0||n==1){
            return 0;
        }else{
            for(int i=1;i<n;i++){
                if(nums[i]<=nums[i-1]){
                    int temp=nums[i-1]-nums[i]+1;
                    res+=temp;
                    nums[i]=temp+nums[i];   
                }
            }
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值