系列文章目录
【拒绝算法PUA】0x00-位运算
【拒绝算法PUA】0x01- 区间比较技巧
【拒绝算法PUA】0x02- 区间合并技巧
【拒绝算法PUA】0x03 - LeetCode 排序类型刷题
【拒绝算法PUA】LeetCode每日一题系列刷题汇总-2025年持续刷新中
C++刷题技巧总结:
[温习C/C++]0x04 刷题基础编码技巧
LeetCode 2264. 字符串中最大的 3 位相同数字
链接
题目
给你一个字符串 num ,表示一个大整数。如果一个整数满足下述所有条件,则认为该整数是一个 优质整数 :
该整数是 num 的一个长度为 3 的 子字符串 。
该整数由唯一一个数字重复 3 次组成。
以字符串形式返回 最大的优质整数 。如果不存在满足要求的整数,则返回一个空字符串 "" 。
注意:
子字符串 是字符串中的一个连续字符序列。
num 或优质整数中可能存在 前导零 。
示例 1:
输入:num = "6777133339"
输出:"777"
解释:num 中存在两个优质整数:"777" 和 "333" 。
"777" 是最大的那个,所以返回 "777" 。
示例 2:
输入:num = "2300019"
输出:"000"
解释:"000" 是唯一一个优质整数。
示例 3:
输入:num = "42352338"
输出:""
解释:不存在长度为 3 且仅由一个唯一数字组成的整数。因此,不存在优质整数。
提示:
3 <= num.length <= 1000
num 仅由数字(0 - 9)组成
解题方法1
#include <iostream>
#include <stack>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
private:
stack<char> book;
vector<int> data;
public:
string largestGoodInteger(string num) {
for (auto iter = num.begin(); iter != num.end(); iter++) {
if (book.empty() || *iter == book.top()) {
char cc = *iter;
book.push(cc);
if (book.size() >= 3) {
string single_num;
single_num.push_back(book.top());
single_num.push_back(book.top());
single_num.push_back(book.top());
data.push_back(stoi(single_num));
while (!book.empty()) {
book.pop();
}
}
continue;
}
// 栈顶元素不等于当前元素
while (book.size() > 0) {
book.pop();
}
book.push(*iter);
};
std::sort(data.begin(), data.end(), std::greater<int>());
if (data.size() > 0) {
int first = data[0];
return first == 0 ? "000" : std::to_string(first);
}
return "";
}
};