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

目录

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

题目解析

C++代码

Java代码


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

游游的字母串

描述:

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

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

输入描述:

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

输出描述:

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


题目解析

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

C++代码

cpp 复制代码
#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代码

cpp 复制代码
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);
    }
}
相关推荐
phltxy8 小时前
C语言操作符详解
java·c语言·算法
RuoZoe8 小时前
从 2026 年 3 月 1 日开源,到 26.10.9:Jalium UI 半年时间到底走了多远?
c语言·c++
aqiu1111119 小时前
【LeetCode 902】最大为 N 的数字组合 - 详细题解与数位组合思路
数据结构·算法·leetcode·蓝桥杯·数位dp
步行cgn9 小时前
@Configuration 详解:Spring 配置类的核心注解
java·后端·spring
sunshine22 girl9 小时前
Java学习一 环境配置2 安装和基本使用Idea
java·学习·intellij-idea
辰烨chenye9 小时前
LeetCode Hot 100 题解 · 哈希篇
算法·leetcode·哈希算法
罗西的思考10 小时前
DreamZero 与 DreamDojo:世界模型与策略的分层协同综合分析与对比
人工智能·算法·机器学习
鱼子星_10 小时前
【C++】继承和多态(上)
c++·笔记
玖玥拾10 小时前
LeetCode 219 存在重复元素 II
算法·leetcode·哈希算法·散列表