一.知识点
1.队列(queue)
定义 queue p;
p.push(1);//插入1
p.front();//访问头
p.pop();//删除头
p.size();//返回元素数量
2.栈(stack)
定义 stack p;
p.push(1);//插入1
p.top();//访问头
p.pop();//删除头
p.size();//返回元素数量
二.题解
1.扩号匹配问题
题意:在某个字符串(长度不超过100)中有左括号、右括号和大小写字母;规定(与常见的算数式子一样)任何一个左括号都从内到外与在它右边且距离最近的右括号匹配.写一个程序,找到无法匹配的左括号和右括号,输出原来字符串,并在下一行标出不能匹配的括号.不能匹配的左括号用“$”标注,不能匹配的右括号用“?”标注.
思路:用栈来匹配,括号匹配上就弹出,没匹配就放入
#include<stdio.h>
#include<stack>
#include<string.h>
using namespace std;
char s[100100]={0};
int n;
int main(){
scanf("%d",&n);
scanf(" %s",s);
int ll=strlen(s);
stack<char> q;
for(int i=0;i<ll-n;i++){
while(q.size()&&s[i]<q.top()) q.pop();
q.push(s[i]);
}
for(int i=ll-n;i<ll;i++)
{
while(q.size()>n+i-ll&&s[i]<q.top()) q.pop();
q.push(s[i]);
}
while(q.size()>n) q.pop();
stack<char> p;
while(!q.empty()){
p.push(q.top());
q.pop();
}
while(!p.empty()){
printf("%c",p.top());
p.pop();
}
printf("\n");
return 0;
}
2.Smallest Substring
题意:Given a string S and an integer K, your task is to find the lexicographically smallest string T which satisfies:
-
T is a subsequence of S
-
The length of T is K.
思路:用数组来模拟栈
#include<stdio.h>
#include<stack>
#include<string.h>
using namespace std;
char s[100100]={0};
int n;
int main(){
scanf("%d",&n);
scanf(" %s",s);
int ll=strlen(s);
stack<char> q;
for(int i=0;i<ll-n;i++){
while(q.size()&&s[i]<q.top()) q.pop();
q.push(s[i]);
}
for(int i=ll-n;i<ll;i++)
{
while(q.size()>n+i-ll&&s[i]<q.top()) q.pop();
q.push(s[i]);
}
while(q.size()>n) q.pop();
stack<char> p;
while(!q.empty()){
p.push(q.top());
q.pop();
}
while(!p.empty()){
printf("%c",p.top());
p.pop();
}
printf("\n");
return 0;
}