例题6-4 UVa11988-Broken Keyboard (a.k.a. Beiju Text)(用不同于紫书的两种办法解决!)

这道题目紫书上给出的解法是使用数组模拟链表,个人认为不大好理解。所以尝试了新的办法:栈+双向队列以及双向链表。具体的细节都在注释里给出。其实还想用单向链表实现一下,等明天有时间再写吧。

题目链接:UVa 11988

AC代码①:双向链表

#include <iostream>
#include <list>
using namespace std;

int main() {
	string s;
	while (cin >> s) {
		list<char> l;
		auto p = l.begin();
		for (int i = 0; i < s.length(); i++) {
			if (s[i] == '[')
				p = l.begin();  //遇到'[',从句首开始插入
			else if (s[i] == ']')
				p = l.end();  //遇到']',回到句尾
			else 
				l.insert(p,s[i]); //第一个参数指定位置,第二个参数指定内容
		}
		for (auto& f : l)
			cout << f;
		cout << endl;
	}
}

AC代码②:栈+双向队列

#include <iostream>
#include <stack>
#include <deque>
//#include <fstream>
using namespace std;

stack<char> word;  //存放将要写入句首的内容
deque<char> text;  //整篇内容

int main() {
	string s;
	//ofstream out("C:\\Users\\Acer\\Desktop\\1.txt");
	while (cin >> s) {
		string str;
		bool flag = false;
		while (!word.empty())
			word.pop();
		text.clear();
		for (int i = 0; i < s.length(); i++) {
			if (s[i] == '[') {
				if(!word.empty())  //如果两个连续的'['之间有内容,则先将这些内容添加到句首
					while (!word.empty()) {
						text.push_front(word.top());
						word.pop();
					} 
				flag = true;
			}
			else if (s[i] == ']')
				flag = false;
			else {
				if (flag)
					word.push(s[i]);
				else
					text.push_back(s[i]);
			}
			if (!word.empty() && (i == s.length() - 1 || !flag))  //当遇到']'或到句子末尾都没有遇到']'时,也要添加word的内容到句首
				while (!word.empty()) {
					text.push_front(word.top());
					word.pop();
				}
		}
		//if (out.is_open()) {
		for (auto& d : text)
			cout << d;
		cout << endl;
		//}
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值