题目大意:给出一串字符,表示从键盘输入的字符,字符里面的’[‘表示键盘的home键,’]’表示键盘的end键,现要求输出这字符串在显示器上的显示
解题思路:链表,处理时要小心.
我是记录该字符串在原字符串中的起始位置,遇到左右中括号就改成’\0’
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define maxn 100010
struct Node {
char *str;
Node *next;
};
char num[10] = {'\0'};
char str[maxn];
int main() {
while(gets(str)) {
int len = strlen(str);
Node *first = new Node();
Node *end = first, *start = first;
first->next = NULL;
first->str = num;
bool flag = 0;
int j;
for(int i = 0; i < len; i++) {
Node *tmp = new Node();
if(str[i] == '[' || str[i] == ']') {
if(str[i] == ']')
flag = false;
else
flag = true;
continue;
}
tmp->str = &str[i];
for(j = i; j < len; j++)
if(str[j] == '[' || str[j] == ']')
break;
if(!flag) {
end->next = tmp;
tmp->next = NULL;
end = tmp;
}
else {
tmp->next = start;
start = tmp;
}
if(str[j] == ']')
flag = 0;
else
flag = 1;
i = j;
str[i] = '\0';
}
while(start != NULL) {
printf("%s",start->str);
start = start->next;
}
printf("\n");
}
return 0;
}
思路2:用两个数组,left从左往右记录,right从右往左记录字符,
比如AB[C]D[E(ABCDE都是代表字符串)
left记录的顺序是ABD
right记录的是CD,只不过CD里面的字符是倒叙存放的
输出的时候先输出right数组,从最后一个字符到第一个字符,然后再输出left,记得加上’\0’
#include<cstdio>
#include<cstring>
using namespace std;
#define maxn 100010
char str[maxn], left_str[maxn], right_str[maxn];
int main() {
while(gets(str)) {
int len = strlen(str), left = 0, right = 0, j;
bool flag = false;
for(int i = 0; i < len; i++) {
for(j = i; j < len; j++)
if(str[j] == '[' || str[j] == ']')
break;
if(!flag) {
for(int k = i; k < j; k++)
left_str[left++] = str[k];
}
else {
for(int k = j - 1; k >= i; k--)
right_str[right++] = str[k];
}
if(str[j] == ']')
flag = false;
else
flag = true;
i = j;
}
left_str[left] = '\0';
for(int i = right - 1; i >= 0; i--)
printf("%c",right_str[i]);
printf("%s\n",left_str);
}
return 0;
}