stack 用法(先进后出):
#include<stack>
stack<int> st;
接口函数:
push() 插入一个元素到栈顶;
top()返回顶层元素;
pop()移除栈顶元素;
size()返回栈中的元素个数;
empty()返回stack是否为空(空返回true,非空返回false);
例题:(hdoj 1274 展开字符串)
思路:
1.如果是左括号,或者数字则直接压入栈中
2.如果是字母
2.1 判断栈顶是不是数字num,如果是循环num次,把字母压入栈
2.2 如果不是直接压入栈
3.如果是右括号
3.1 将括号内的字符存入temp数组中,并把这些字符出栈
3.1.1 然后看栈顶,如果是数字则循环多次,将temp压入栈中
3.1.2 如果不是直接压入栈中
4.最后将栈中所有元素存入数组ans,并输出;
代码如下:
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <math.h>
#include <cmath>
#include <string.h>
#include <stack>
#include<string>
using namespace std;
int is_num(char a)
{
if (a >= '1'&&a <= '9')
return 1;
else
return 0;
}
int main()
{
stack <char >a;
int n;
char s[1000];
string temp;
string ans;
int len;
int num;
int i, j;
cin >> n;
while (n--)
{
cin >> s;
ans.clear();
temp.clear();
len = strlen(s);
for (i = 0; i<len; i++)
{
if (is_num(s[i]) || s[i] == '(')
a.push(s[i]);
else if (s[i] >= 'a'&&s[i] <= 'z')
{
if (is_num(a.top()))
{
num = a.top()-'0';
a.pop();
while (num--)
a.push(s[i]);
}
else
a.push(s[i]);
}
else
{
while (a.top() != '(')
{
temp.insert(temp.begin(), a.top());
a.pop();
}
a.pop();
if (is_num(a.top()))
{
num = a.top() - '0';
a.pop();
}
else
{
num = 1;
}
while (num--)
{
for (j = 0; j<temp.size(); j++)
{
a.push(temp[j]);
}
}
temp.clear();
}
}
while (!a.empty())
{
ans.insert(ans.begin(), a.top());
a.pop();
}
cout << ans << endl;
}
return 0;
}