先贴上题目
这个题目从开始思考,到最终得到“答案正确”的时间跨度很长,主要原因有:
1. 题目要求分析不清
2. 实现时,出现几个困难点:
* 1 如何读入多个字符串?(最初出现问题可能是由于没有注意到题目中要求字符串长度不超过100)
* 2 数组元素个数未知,如何避免出现错误?
How to understand the question?
Requirement 1: only ‘P’ ,’A’ and ‘T’ are in the string
Requirement 2: xPATx is right. Caution! The string before ‘P’ and after ‘T’ are the same!(L)
Requirement 3: if “aPbTc” is right, “aPbATca” is right. “The string is right” exactly means that when it occurs, it is right. There is no problem of the sequence of appearance.
(x ,a ,b ,c are all srings conposed of only ‘A’ or only ’ ‘)
So, when you finish reading these requirements, what do you get?
You can try to back-infer the string with one A between ‘P’ and ‘T’(L), or?
Write the requirements down! You will find the numbers of A in different positions have a variation curve.
a3 = a2 * a1 (a2 != 0).
This is the code.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int i ,j ,n ,p ,t ,a1 = 0 ,a2 = 0 ,a3 = 0 ,oth;
// i,j: counter n: the size of the array p: number of 'P' t: number of 'T' oth: number of characters except 'P', 'T' or'A'
// a1: number of 'A' in front of 'P'
// a2: number of 'A' between 'P' and 'T'
// a3: number of 'A' that appears after 'T'
char * str[10];
unsigned long len = 0;
scanf ("%d" , &n);
for (i = 0 ;i < n ;i++)
str[i] = (char *)malloc(sizeof(char)*100);
//Problem 1: thread 1:exc_bad_access(code=2,address=Ox7fff5fc00000)
for (i = 0 ;i < n ;i++)
scanf ("%s" , str[i]);
for (i = 0 ;i < n ;i++)
{
p = 0;
t = 0;
oth = 0;
//Problem 2: Forget to give the initial number '0' to p, t and oth
for (j = 0 ;str[i][j] != '\0' ;j++)
{
if (str[i][j] == 'P')
p++;
else
if (str[i][j] == 'T')
t++;
else
if (str[i][j] != 'A')
oth++;
}
if (p != 1 || t != 1 || oth)
printf("NO\n");
//Judged from p, t and oth, I will know if there is one P, one T, and no other characters in the string.
else
{
len = strlen(str[i]);
if (strchr (str[i],'P') < strchr (str[i],'T'))
{
for (j = 0 ;str[i][j] != 'P' ;j++);
a1 = j;//find how many A before P
for (j = 0 ;str[i][j] != 'T' ;j++);
//Problem 3: Forget to test if 'P' is in front of 'T', the problem “a segmentation fault” to occur
//str[i][j] = 'T'
a2 = j - a1 - 1;//how many A between P and T
a3 = (int)len - (j + 1);//how many A that appears after T
//Suppose: a3 = a2 * a1;Right!
if (a3 == a2 * a1 && a2 != 0)
printf ("YES\n");
else
printf("NO\n");
}
else printf("NO\n");
}
}
return 0;
}
另:
1. Problem 1: I searched the Internet.
2. 关于“段错误”问题可以深究