试探讨暴风影音2014笔试题
笔试题一:
解题思路:
使用一个指针i对输入字符串进行扫描,统计出最深的层次,指针start和end分别指向最深的左括号和右括号,如下图所示
测试效果:
代码:
/* * 2014 BaoFengYingYin XiaoYuan Recruitment * to find a deepest expression in a string * Input: X + ((Y - 6) * 2) + (((2 * 3) / 2Y) + I) / (2 * 6Y) * Output: 2 * 3 * */#include <stdio.h>#include <stdlib.h>#include <string.h>#define SIZE 1024int DeepestMatch(char *str) { int i; int lay, maxlay; // the lay of Kuhao int start, end; int check; // whether the Kuhao match maxlay = 0; lay = 0; check = 0; for(i = 0;str[i];i++) {if(str[i] == '(') { lay++; check++;}else if(str[i] == ')') { check--; if(lay > maxlay) {maxlay = lay;end = i;lay = 0; }} } if(check) {perror("Kuhao Mismatch!\n");exit(EXIT_FAILURE); } if(!maxlay) {perror("there is no kuhao in the expression!\n");return 0; } start = end; while(str[start] != '(') start--; puts("the deepest expression in the string is:"); for(i = start+1;i < end;i++) {putchar(str[i]); } putchar('\n'); return 0;}int main() { char str[SIZE]; memset(str, 0, sizeof(str)); printf("Input a expression:"); gets(str); DeepestMatch(str); return 0;}