每日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);
    }
}
相关推荐
鶴哥只手遮天2 分钟前
Spring Boot 4.1.1 深度源码解析-第 13 章 · Bean 定义加载:`BeanDefinitionLoader`、组件扫描与 Bean 命名
java·后端·开源
鶴哥只手遮天3 分钟前
Spring Boot 4.1.1 深度源码解析-第 18 章 内嵌 Web 服务器:`WebServer` 抽象与 Tomcat/Jetty/Netty
java·后端·开源
wzdark4 分钟前
动态规划算法的状态转移矩阵可视化分析5
算法·矩阵·动态规划
泡茶喝茶写代码4 分钟前
A股量化策略回测实战:从行情数据到绩效评估(第 1 篇):回测引擎从零搭建
java·python·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口
鶴哥只手遮天4 分钟前
Spring Boot 4.1.1 深度源码解析-第 10 章 · Profile 与多文档:`spring.config.activate`
java·后端·开源
鶴哥只手遮天5 分钟前
Spring Boot 4.1.1 深度源码解析-第 06 章 · Environment 构建:PropertySource 次序
java·后端·开源
鶴哥只手遮天5 分钟前
Spring Boot 4.1.1 深度源码解析-第 09 章 · `@ConfigurationProperties` 全生命周期:注册、绑定、校验与 AOT
java·后端·开源
Pniubi8 分钟前
力扣70爬楼梯
数据结构·算法·leetcode
Wang's Blog10 分钟前
Java 项目实战: 交友项目 - 百度人脸识别:抽取自动装配组件
java·百度·交友
鶴哥只手遮天10 分钟前
Spring Boot 4.1.1 深度源码解析-第 08 章 · Binder 绑定引擎:从字符串到 Java 对象的完整路径
java·后端·开源