腾讯音乐娱乐集团2023校园招聘技术类岗位编程题合集

1.字符串操作

给定一个只包含小写字母字符串,每次可以选择两个相同的字符删除,并在字符串结尾新增任意一个小写字母。
请问最少多少次操作后,所有的字母都不相同?

public int minOperations (String str) {
        // write code here
        int[] count=new int[26];
        for(char c:str.toCharArray()){
            count[c-'a']++;
        }
        int sum=0;
        int res=0;
        int nocount=0;
        for(int i=0;i<26;i++){
            sum+=count[i]/2;
            count[i]%=2;
            if(count[i]==0)
                nocount++;
        }
        if(sum<nocount) return sum;
        res=sum+sum-nocount;
        return res;
    }

给定一棵二叉树,二叉树的每个结点只有0或2个孩子。

    public int getTreeSum (TreeNode tree) {
        // write code here
        int ans=1,k=height(tree);
        while(k>=0){
            ans=ans*2;
            ans%=1000000007;
            k--;
        }
        return ans-1;
    }
    int height(TreeNode tree){    
        if(tree==null) return -1;
        return 1+Math.max(height(tree.left),height(tree.right));
    }

4.01串修改

给定一个只包含’0’和’1’两种字符的字符串,每次操作可以选择相邻的两个字符,将它们同时变成’0’或者同时变成’1’。
请问最少多少次操作后,所有的字符都相同?

public int minOperations (String str) {
        // write code here
        int num0=0,num1=0;
        int i=0;
        while(i<str.length()){
            int st=i;
            if(str.charAt(i)=='0'){
                while(i<str.length()&&str.charAt(i)=='0'){
                    ++i;
                }
                num0+=(i-st)/2;
                num0+=(i-st)%2;
            }
            else{
                while(i<str.length()&&str.charAt(i)=='1'){
                    ++i;
                }
                num1+=(i-st)/2;
                num1+=(i-st)%2;
            }

        }
        return Math.min(num0,num1);
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杰米的大鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值