数据结构

一.知识点
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:

  1. T is a subsequence of S

  2. 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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值