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

【C++算法】模拟算法

替换所有的问号

  • 题目链接

替换所有的问号icon-default.png?t=O83Ahttps://leetcode.cn/problems/replace-all-s-to-avoid-consecutive-repeating-characters/description/

  • 算法原理

  • 代码步骤
class Solution {
public:string modifyString(string s) {int n = s.size();for(int i = 0; i < n; i++){if(s[i] == '?'){for(int j = 'a'; j <= 'z'; j++){if((i == 0 || s[i - 1] != j) && (i == n - 1 || s[i + 1] != j)){s[i] = j;break;}}}}return s;}
};

提莫攻击

  • 题目链接

提莫攻击icon-default.png?t=O83Ahttps://leetcode.cn/problems/teemo-attacking/description/

  • 算法原理

  • 代码步骤
class Solution {
public:int findPoisonedDuration(vector<int>& timeSeries, int duration) {int ret = 0;for(int i = 1; i < timeSeries.size(); i++){int x = timeSeries[i] - timeSeries[i - 1];if(x >= duration) ret += duration;else ret += x;}return ret + duration;}
};

Z字形变换

  • 题目链接

Z字型变换icon-default.png?t=O83Ahttps://leetcode.cn/problems/zigzag-conversion/description/

  • 算法原理

  • 代码步骤
class Solution {
public:string convert(string s, int numRows) {if(numRows == 1){return s;}int n = s.size();int d = 2 * numRows - 2;string ret;// 第一行for(int i = 0;i < n; i += d){ret += s[i];}// 中间行for(int i = 1; i < numRows - 1; i++){for(int j = i, k = d - i; j < n || k < n; j += d, k += d){if(j < n) ret += s[j];if(k < n) ret += s[k];}}// 最后一行for(int i = numRows - 1; i < n; i += d){ret += s[i];}return ret;}
};

外观数列

  • 题目链接

外观数列icon-default.png?t=O83Ahttps://leetcode.cn/problems/count-and-say/description/

  • 算法原理

  • 代码步骤
class Solution {
public:string countAndSay(int n) {string s = "1";for(int i = 2; i <= n; i++){string tmp;for(int left = 0, right = 0; right < s.size(); ){while(right < s.size()){if(s[left] != s[right]) break;right++;}tmp += to_string(right - left) + s[left];left = right;}s = tmp;}return s;}
};

数青蛙

  • 题目链接

数青蛙icon-default.png?t=O83Ahttps://leetcode.cn/problems/minimum-number-of-frogs-croaking/description/

  • 算法原理

  • 代码步骤
class Solution {
public:int minNumberOfFrogs(string croakOfFrogs) {string s = "croak";int n = s.size();vector<int> ret(n);// 哈希找下表unordered_map<char, int> hash;for(int i = 0; i < n; i++){hash[s[i]] = i;}for(auto ch : croakOfFrogs){if(ch == 'c'){if(ret[n - 1] != 0){ret[n - 1]--;ret[0]++;}else{ret[0]++;}}else{if(ret[hash[ch] - 1] != 0){ret[hash[ch] - 1]--;ret[hash[ch]]++;}else{return -1;}}}for(int i = 0; i < n - 1; i++){if(ret[i] != 0) return -1;}return ret[n - 1];}
};

http://www.mrgr.cn/news/30439.html

相关文章:

  • 【MySQL】表的相关操作
  • linux网络编程3
  • 项目实现:云备份服务端①(文件操作、Json等工具类实现)
  • 建设工程联合体的性质如何认定?
  • 【机器学习】经典数据集鸢尾花的分类识别
  • Yocto - 使用Yocto开发嵌入式Linux系统_01 前言
  • 模型训练时CPU和GPU大幅度波动——可能是数据的读入拖后腿
  • OJ在线评测系统 思考主流OJ的实现方案 常用概念 自己的思考
  • Win32 Wmi获取设备信息
  • 总结拓展十:SAP开发计划(下)
  • ①原装进口芯片一主多从RS485通讯转换器从站转地址波特率转校验位转寄存器转停止位modbus协议转换中继器
  • 进入C++
  • Python的基础知识,帮助初学者快速上手
  • Java键盘输入语句
  • 大模型-模型架构-长上下文模型
  • 3.使用 VSCode 过程中的英语积累 - Selection 菜单(每一次重点积累 5 个单词)
  • 面试官:什么是CAS?存在什么问题?
  • 【海康威视面经】
  • gcc升级(含命令行升级、手动升级两种方式)
  • 数据结构之二叉树遍历