用c++实现。 给定一个由大写字母组成的长度为 n 的字符串,请在字符串中删除 m 个字符,使得剩下的字符串的字典序最小。
时间: 2024-06-13 18:06:03 浏览: 25
以下是C++实现的代码:
```cpp
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main() {
string s;
int m;
cin >> s >> m;
stack<char> stk;
for (char c : s) {
while (m && !stk.empty() && stk.top() > c) {
stk.pop();
m--;
}
stk.push(c);
}
while (m--) {
stk.pop();
}
string ans = "";
while (!stk.empty()) {
ans += stk.top();
stk.pop();
}
reverse(ans.begin(), ans.end());
cout << ans << endl;
return 0;
}
```
相关问题
c++给定一个由大写字母组成长度为n的字符串,请在字符串中删除m个字符,使得剩下的字符串的字典序最小
以下是C++实现给定一个由大写字母组成长度为n的字符串,请在字符串中删除m个字符,使得剩下的字符串的字典序最小的代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
int m;
cin >> s >> m;
string ans = "";
for (char c : s) {
while (m && ans.size() && ans.back() > c) {
ans.pop_back();
m--;
}
ans.push_back(c);
}
while (m--) ans.pop_back();
cout << ans << endl;
return 0;
}
```
使用C++代码实现 给定一个由大写字母组成的长度为 n 的字符串,请在字符串中删除 m 个字符,使得剩下的字符串的字典序最小。
以下是使用C++代码实现给定一个由大写字母组成的长度为 n 的字符串,请在字符串中删除 m 个字符,使得剩下的字符串的字典序最小的方法:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
int m;
cin >> s >> m;
string ans = "";
for (char c : s) {
while (m && ans.size() && ans.back() > c) {
ans.pop_back();
m--;
}
ans.push_back(c);
}
while (m--) ans.pop_back();
cout << ans << endl;
return 0;
}
```