请用c++代码实现上述题目
时间: 2024-03-14 14:44:06 浏览: 22
以下是 C++ 代码实现:
```cpp
#include <iostream>
#include <string>
#include <stack>
#include <unordered_map>
using namespace std;
int main() {
string s;
while (getline(cin, s)) {
stack<int> st;
unordered_map<int, int> mp;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(') {
st.push(i);
} else if (s[i] == ')') {
if (!st.empty()) {
mp[st.top()] = i;
st.pop();
} else {
mp[i] = -1;
}
}
}
string res(s.size(), ' ');
for (auto it : mp) {
if (it.second == -1) {
res[it.first] = '$';
} else {
res[it.first] = ' ';
res[it.second] = ' ';
}
}
cout << s << endl;
cout << res << endl;
}
return 0;
}
```
与 Python3 代码类似,使用栈和哈希表来记录左右括号的匹配关系,最后输出标记结果即可。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)