Simple Line Editor
Description
Early computer used line editor, which allowed text to be created and changed only within one line at a time. However, in line editor programs, typing, editing, and document display do not occur simultaneously (unlike the modern text editor like Microsoft Word). Typically, typing does not enter text directly into the document. Instead, users modify the document text by entering simple commands on a text-only terminal.
Here is an example of a simple line editor which can only process English. In addition, it has two commands. ‘@’ and ‘#’. ‘#’ means to cancel the previous letter, and ‘@’ is a command which invalidates all the letters typed before. That is to say, if you want type “aa”, but have mistakenly entered “ab”, then you should enter ‘#a’ or ‘@aa’ to correct it. Note that if there is no letter in the current document, ‘@’ or ‘#’ command will do nothing.
Input
The first line contains an integer T, which is the number of test cases. Each test case is a typing sequence of a line editor, which contains only lower case letters, ‘@’ and ‘#’.
Output
For each test case, print one line which represents the final document of the user. There would be no empty line in the test data.
Sample Input
2
ab#a
ab@aa
Sample Output
aa
aa
HINT
以下为原作者思路及代码
找到之前的错误了:
else if (ch=='#' && i>=0) --i;
初始条件是 i = -1; 这样i = - 1;时,如果输入“#”,应该被忽略,但这句话其实没有做到。
应该这样写:
else if (t[i]=='#') j = (j>=0 ? j-1:-1);
由于题目中没有提到一行文本到底有多少字符,干脆定义最大为 100 吧,什么?竟然通过了!
实际上只用一个 getcha() 和一个数组就行了,使用了栈。
# include <stdio.h>
# include <string.h>
# define MAXN 100
char t[MAXN], s[MAXN];
int T;
int main()
{
int i, j, len;
scanf("%d", &T);
getchar();
while (T--)
{
fgets(t, MAXN, stdin);
len = strlen(t);
for (j = i = 0; i < len; ++i)
if (t[i] == '@') j = 0;
else if (t[i]=='#') j = (j>0 ? j-1:0);
else s[j++] = t[i];
s[j] = '\0';
fputs(s, stdout);
}
return 0;
}