每日OJ_牛客_游游的字母串_枚举_C++_Java

目录

牛客_游游的字母串_枚举

题目解析

C++代码

Java代码


牛客_游游的字母串_枚举

游游的字母串

描述:

对于一个小写字母而言,游游可以通过一次操作把这个字母变成相邻的字母。'a'和'b'相邻,'b'和'c'相邻,以此类推。特殊的,'a'和'z'也是相邻的。可以认为,小写字母的相邻规则为一个环。

游游拿到了一个仅包含小写字母的字符串,她想知道,使得所有字母都相等至少要多少次操作?

输入描述:

一个仅包含小写字母,长度不超过100000的字符串。

输出描述:

一个整数,代表最小的操作次数。


题目解析

        英文字母一共就26个,因此可以直接暴力枚举以每个字母作为最后的转变字母。最后去最小值即可。

C++代码

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    string str;
    cin >> str;
    int res = 1e9;
    for(char ch = 'a'; ch <= 'z'; ++ch)
    {
        int cnt = 0;
        for(auto e : str)
        {
            cnt += min(abs(e - ch), 26 - abs(e - ch));
        }
        res = min(res, cnt);
    }
    cout << res << endl;
    return 0;
}

Java代码

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        char[] s = in.next().toCharArray();

        int ret = (int)1e9;
        for(char ch = 'a'; ch <= 'z'; ch++)
        {
            int sum = 0;
            for(int i = 0; i < s.length; i++)
            {
                sum += Math.min(Math.abs(s[i] - ch), 26 - Math.abs(s[i] - ch));
            }
            ret = Math.min(ret, sum);
        }

        System.out.println(ret);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

GR鲸鱼

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

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

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

打赏作者

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

抵扣说明:

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

余额充值