题目链接:leetcode.
/*
执行用时:4 ms, 在所有 C++ 提交中击败了42.13%的用户
内存消耗:6.4 MB, 在所有 C++ 提交中击败了41.57%的用户
*/
class Solution {
public:
string reverseParentheses(string s) {
stack<pair<char, int>> stk;
stack<int> index;
int N = s.size();
for(int i = 0;i < N;++i)
{
if(s[i] == '(')
{
index.push(i);
}
else if(s[i] == ')')
{
int end = index.top();
index.pop();
string tmp = "";
while(!stk.empty())
{
if(stk.top().second > end)
{
tmp += stk.top().first;
stk.pop();
}
else
{
break;
}
}
for(auto c : tmp)
{
stk.push({c, ++end});
}
}
else
{
stk.push({s[i], i});
}
}
string ans = "";
while(!stk.empty())
{
ans += stk.top().first;
stk.pop();
}
reverse(ans.begin(), ans.end());
return ans;
}
};
题解好像更简单呢
用栈存已经遍历了的字符串
每次碰到(,就把当前字符串入栈,然后开始记录需要翻转的字符串,直到遇到),就该结束了,把记录的字符串翻转,然后和栈中的拼接
/*
执行用时:0 ms, 在所有 C++ 提交中击败了100.00%的用户
内存消耗:6.5 MB, 在所有 C++ 提交中击败了33.39%的用户
*/
class Solution {
public:
string reverseParentheses(string s) {
int N = s.size();
stack<string> stk;
string str = "";
for(auto c : s)
{
if(c == '(')
{
stk.push(str);
str = "";
}
else if(c == ')')
{
reverse(str.begin(), str.end());
string tmp = stk.top();
stk.pop();
str = tmp + str;
}
else
{
str += c;
}
}
return str;
}
};
这篇博客介绍了两种不同的C++解决方案来处理LeetCode上的括号反转问题。第一种方法利用两个栈,分别存储字符和它们的索引,遇到'('入栈,遇到')'时翻转栈内字符串并拼接。第二种方法更简洁,只用一个栈,遇到'('将当前字符串入栈,遇到')'时翻转栈顶字符串并拼接。这两种方法都实现了在O(n)的时间复杂度内完成题目要求,但第二种方法在空间效率上更优。
677

被折叠的 条评论
为什么被折叠?



