例题6-4 破损的键盘(又名:悲剧文本)(Broken Keyboard(a.k.a. Beiju Text), UVa 11988)

#ifdef _DEBUG
#pragma warning(disable : 4996)
#endif
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <algorithm>
#include <functional>
#include <sstream>
#include <utility>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <cctype>
#define CLEAR(a, b) memset(a, b, sizeof(a))
#define CLOSE() ios::sync_with_stdio(false)
#define IN() freopen("in.txt", "r", stdin)
#define OUT() freopen("out.txt", "w", stdout)
#define PF(a) printf("%d\n", a)
#define SF(a) scanf("%d", &a)
#define SFF(a, b) scanf("%d%d", &a, &b)
#define FOR(i, a, b) for(int i = a; i < b; ++i)
#define LL long long
#define maxn 100005
#define mod 1000007
#define INF 1e15
using namespace std;
//------------------------------------------------------------------------------------------//
typedef struct Node *List;
struct Node {
	char ch;
	Node *next;
};

List Create(char ch) {
	List head = new(Node);
	head->ch = ch;
	head->next = nullptr;
	return head;
}

void Insert(List pos, List L) {
	L->next = pos->next;
	pos->next = L;
}

void Print(List head) {
	List p = head->next;
	while (p != nullptr) {
		printf("%c", p->ch);
		p = p->next;
	}
}

int main() {
	string msg;
	while (cin >> msg) {
		List last, cur, L = Create(0);
		last = cur = L;
		FOR(i, 0, msg.size()) {
			if (msg[i] == '[') {
				cur = L;
			}
			else if (msg[i] == ']') {
				cur = last;
			}
			else {
				List node = Create(msg[i]);
				Insert(cur, node);
				if (cur == last) last = node;
				cur = node;
			}
		}
		Print(L);
		puts("");
	}
	return 0;
}


//看了lrjls的代码,发现自己学的还是太死板了,链表只是一种思想,用数组同样可以表示。
//主要在于模拟出光标cursor的位置,每次添加在cursor之后


int next[maxn];
char str[maxn];

int main() {
	int cur, last;
	while (scanf("%s", str+1) == 1) {
		int n = strlen(str + 1);
		cur = last = 0;
		next[0] = 0;
		FOR(i, 1, n + 1) {
			if (str[i] == '[') cur = 0;
			else if (str[i] == ']') cur = last;
			else {
				next[i] = next[cur];
				next[cur] = i;
				if (cur == last) last = i;
				cur = i;
			}
		}
		for (int i = next[0]; i != 0; i = next[i]) printf("%c", str[i]);
		puts("");
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值