【转载请注明出处: http://blog.csdn.net/lzl124631x】
OJ: https://code.google.com/codejam/contest/2929486/dashboard#s=p4
思路:
- 按行为单位输入.
- 设置level标志指示当前在注释的第几层中, 初始为0.
- 普通文本状态(level == 0)下正常读入, 当遇到"/*"时level++.
- 注释状态(level > 0)下跳过输入, 当遇到"/*"时level++, 遇到"*/"时level--.
- 仅在level == 0的行尾输出'\n'.
代码:
#include <stdio.h>
#define MAX_SIZE 100000
#define COMMENT_START(s) (*(s) == '/' && *((s) + 1) == '*')
#define COMMENT_END(s) (*(s) == '*' && *((s) + 1) == '/')
int main(){
char str_in[MAX_SIZE] = {0};
char str_out[MAX_SIZE] = {0};
char *p_in, *p_out;
int level;
freopen("E-large-practice.in","r",stdin);
freopen("out.txt","w",stdout);
level = 0;
p_out = str_out;
while(gets(str_in)){
p_in = str_in;// new line
while(*p_in){
if(level == 0){// text mode
while(*p_in && !COMMENT_START(p_in)){
*p_out++ = *p_in++;
}
if(*p_in){
p_in += 2; level++;
}
}else{// comment mode
while(*p_in && !COMMENT_START(p_in) && !COMMENT_END(p_in)) p_in++;
if(COMMENT_START(p_in)){
p_in += 2; level++;
}else if(COMMENT_END(p_in)){
p_in += 2; level--;
}
}
}
if(level == 0) *p_out++ = '\n';// output '\n' at end of line in text mode
}
*p_out = 0;
printf("Case #1:\n%s", str_out);
return 0;
}