括号匹配
给定一个只包含’(‘, ‘)’, ‘[‘, ‘]’, ‘{‘, ‘}’的字符串 S,判断字符串是否有效。有效字符串需满足:左
括号必须用相同类型的右括号闭合,左括号必须以正确的顺序闭合。
#include<iostream>
#include<map>//使用map容器
#include<stack>
using namespace std;
string s;
//判断字符串是否有效
void judge(string s)
{
stack<char>a;
for (int i = 0; i < s.length(); i++)
{
if ((s[i] == ')' && a.top() == '(') || (s[i] == '}' && a.top() == '{') || (s[i] == ']' && a.top() == '['))
//若当前s为])}时,若栈顶与其相匹配,则弹栈
{
a.pop();
}
else//若当前s为[({时,直接压入栈中
a.push(s[i]);
}
if (!a.empty())
//若栈内有字符,则说明括号串不完全匹配
{
cout << "字符串无效 " << endl;
}
else cout << "字符串有效 " << endl;
}
int main()
{
int t;//数据组数
cin >> t;
for (int i = 1; i <= t; i++)
{
cin >> s;
judge(s);
}
return 0;
}
/*
2
()(){([])}
({]{}
*/
两个栈实现队列
代码可能有瑕疵,如有问题请指出
请仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push, pop,
peek, empty)
#include<iostream>
#include<map>//使用map容器
#include<stack>
using namespace std;
class myQueue
{
public:
myQueue()
{
}
void push(int x) //压入元素
{
a.push(x);
}
void pop() //弹出元素
{
newflag2();
if (flag2==1)
{
b.pop();
}
else
{
while (!a.empty())
{
int temp = a.top();
a.pop();
b.push(temp);
}
b.pop();
flag2 = 1;
}
}
int peak() //查看队首元素
//注意:若栈b中无元素,就把a中元素导入b中,这样即可实现先入先出
{
newflag2();
if (flag2 == 1)
{
return b.top();
}
else
{
while (!a.empty())
{
int temp = a.top();
a.pop();
b.push(temp);
}
return b.top();
flag2 = 1;
}
}
bool empty() //判断队列是否为空
{
if (b.empty() && a.empty())
{
return 1;
}
else return 0;
}
void newflag2()
{
if (!b.empty())
{
flag2 = 1;
}
else
{
flag2 = 0;
}
}
private:
int flag2 = 0;;
stack<int>a;
stack<int>b;
};
void test(myQueue x)//测试队列是否为空
{
if (!x.empty())
{
cout << "队列不为空" << endl;
}
else
{
cout << "队列为空" << endl;
}
}
int main()
{
myQueue temp;
for (int i = 0; i <= 4; i++)//按顺序将0-4压入队列中
{
temp.push(i);
}
test(temp);
cout << "此时队首为:" << temp.peak() << endl;
temp.pop();
cout << "弹出一个元素后队首为:" << temp.peak()<<endl;
cout << "此时队列为:" << endl;
while (!temp.empty())
{
cout << temp.peak() << " ";
temp.pop();
}
cout << endl;
test(temp);
return 0;
}
下一个最大元素 单调栈
给定两个没有重复元素的数组 nums1 和 nums2,其中 nums1 是 nums2 的子集。请找出
nums1 中每个元素在 nums2 中的下一个更大元素。Nums1 中数字 x 的下一个更大元素是指
x 在 nums2 中对应位置的右边第一个比 x 大的元素。如果不存在,则输出-1。时间复杂度
O(n+m)
#include<iostream>
#include<map>//使用map容器
#include<stack>
using namespace std;
int num1[5005], num2[5005];
//查找下一个更大元素
void search(int num1[],int num2[])
{
stack<int>a;
map<int, int>m;
//此处利用单调栈的思想
a.push(num2[0]);//先将第一个元素压入栈中
for (int i = 1; i < 4; i++)
{
while (!a.empty())
{
int temp = a.top();
if (num2[i] > temp)
{
m.insert(pair<int, int>(temp, num2[i]));//插入map容器,此时栈顶的下一个最大元素即为num2[i]
a.pop();//此时找到栈顶元素的下一个最大元素,即可弹出栈顶
}
else
{
break;
}
}
a.push(num2[i]);
}
while (!a.empty())
{
m.insert(pair<int, int>(a.top(), -1));
a.pop();
}
cout << "输出Nums1 中数字 x 的下一个更大元素数组:" << endl;
for (int i = 0; i < 3; i++)
{
cout << m[num1[i]] << " ";
}
}
int main()
{
for (int i = 0; i < 3; i++)
{
cin >> num1[i];
}
for (int i = 0; i < 4; i++)
{
cin >> num2[i];
}
search(num1, num2);
return 0;
}
/*
4 1 2
1 3 4 2
*/