当前位置: 首页 > news >正文

每日OJ题_牛客_重排字符串_贪心_C++_Java

目录

牛客_重排字符串_贪心

题目解析

C++代码

Java代码


牛客_重排字符串_贪心

重排字符串 (nowcoder.com)

描述:

        小红拿到了一个只由小写字母组成的字符串。她准备把这个字符串重排(只改变字母的顺序,不改变数量)
        重排后小红想让新字符串不包含任意两个相同的相邻字母。你能帮帮她吗?


题目解析

C++代码

#include <climits>
#include <iostream>
#include <vector>
using namespace std;int main()
{int n = 0;string str;cin >> n >> str;vector<int> hash(26, 0);int sz = str.size();for (int i = 0; i < sz; ++i){hash[str[i] - 'a']++;}int maxCnt = 0, maxIndex = 0;for (int i = 0; i < 26; ++i) // 先放第一大{if (hash[i] > maxCnt){maxCnt = hash[i];maxIndex = i;}}if (maxCnt > (sz + 1) / 2)cout << "no";else{cout << "yes" << endl;vector<char> res(n);int i = 0;while (maxCnt--){res[i] = (maxIndex + 'a');i += 2;}// cout << maxIndex << endl;for (int j = 0; j < 26; ++j){if (j != maxIndex && hash[j] != 0) // 找到一个后往后找{while(hash[j]--){if(i >= n)i = 1;res[i] = j + 'a';i += 2;}}}for (auto& e : res){cout << e;}cout << endl;}return 0;
}

Java代码

import java.util.*;
public class Main
{public static void main(String[] args){Scanner in = new Scanner(System.in);int n = in.nextInt();char[] s = in.next().toCharArray();char maxChar = '0';int maxCount = 0;int[] hash = new int[26];// 找出现次数最多的字符以及次数for(int i = 0; i < n; i++){char ch = s[i];if(++hash[ch - 'a'] > maxCount){maxChar = ch;maxCount = hash[ch - 'a'];}}// 判断是否能重排if(maxCount > (n + 1) / 2){System.out.println("no");}else{System.out.println("yes");char[] ret = new char[n];int i = 0;// 重新排列// 1. 先处理出现次数最多的字符while(maxCount-- != 0){ret[i] = maxChar;i += 2;}// 2. 处理剩下的字符for(int j = 0; j < 26; j++){if(hash[j] != 0 && (char)(j + 'a') != maxChar){while(hash[j]-- != 0){if(i >= n){i = 1;}ret[i] = (char)(j + 'a');i += 2;}}}for(int j = 0; j < n; j++){System.out.print(ret[j]);}}}
}
http://www.lryc.cn/news/454585.html

相关文章:

  • Python 进阶部分详细整理
  • [ RK3566-Android11 ] 关于移植 RK628F 驱动以及后HDMI-IN图像延迟/无声等问题
  • 【黑马点评】 使用RabbitMQ实现消息队列——2.使用RabbitMQ监听秒杀下单
  • 业务封装与映射 -- OTUk/ODUk/OPUk开销帧结构
  • Vim基本用法
  • python 实现Tarjan 用于在有向图中查找强连通分量的算法
  • Qt开发技巧(十五)字符串去除空格,跨网段搜索不生效,设置图片显示失败问题,表格视图的批量删除,主动判断字串编码,开启向前查询的属性,画家类载入html来绘制
  • 【机器学习】智驭未来:探索机器学习在食品生产中的革新之路
  • Ubuntu 安装CUDA并使用Docker配置Pytorch环境
  • 【论文阅读】Simulating 500 million years of evolution with a language model
  • detectron2/layers源码笔记
  • LLM+知识图谱新工具! iText2KG:使用大型语言模型构建增量知识图谱
  • React基础-快速梳理
  • H.264编解码 - NALU详解
  • vSAN02:容错、存储策略、文件服务、快照与备份、iSCSI
  • 图解C#高级教程(四):协变、逆变
  • 详解CSS中的伪元素
  • paper_template
  • 【Bug】解决 Ubuntu 中 “error: Unable to Find Python3 Executable” 错误
  • CUDA与TensorRT学习六:模型部署-CNN、模型部署-YOLOv8检测器、部署BEVFusion模型
  • 防sql注入的网站登录系统设计与实现
  • 如何快速切换电脑的ip地址
  • 鸿蒙HarmonyOS之选择相册文件(照片/视频)方法
  • 【QT Qucik】C++交互:接收QML信号
  • 【C++】关键字+命名空间
  • 网络层——IP
  • 随笔 漫游互联网
  • 8.9K Star,开源自托管离线翻译引擎
  • MySQL基础之DML
  • 男单新老对决:林诗栋VS马龙,巅峰之战