http://acm.sgu.ru/problem.php?contest=0&problem=274
判断一个所给字符串是不是有效的email地址,要注意的是题目给的邮箱地址可能中间含有空格。所以要用getline,我用getchar()不知道哪里错了总是TLE on test1。
#include <cctype>
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
bool word(char* s, int a, int b) {
if (a > b) {
return false;
} else {
int i;
for (i = a; i <= b; ++i) {
if (!isalnum(s[i]) && s[i] != '-' && s[i] != '_') {
return false;
}
}
}
return true;
}
bool prefix(char* s, int a, int b) {
if (a > b) {
return false;
}
int i;
for (i = b; i >= a; --i) {
if (s[i] == '.') {
break;
}
}
return (i == a-1) ? word(s, a, b) : word(s, i+1, b) && prefix(s, a, i-1);
}
bool domain(char* s, int a, int b) {
int i;
for (i = a; i <= b; ++i) {
if (!isalpha(s[i])) {
return false;
}
}
return (b-a)>=1 && (b-a)<=2;
}
bool suffix(char* s, int a, int b) {
int i;
for (i = b; i >= a; --i) {
if (s[i] == '.') {
break;
}
}
return prefix(s, a, i-1) && domain(s, i+1, b);
}
bool address(char* s, int a, int b) {
int i;
for (i = a; i <= b; ++i) {
if (s[i] == '@') {
break;
}
}
return prefix(s, a, i-1) && suffix(s, i+1, b);
}
int main(void) {
char email[102];
string s;
int n;
cin >> n;
//scanf ("%d", &n);
while (getchar() != '\n');
while (n--) {
getline(cin, s);
strcpy(email, s.c_str());
if (address(email, 0, strlen(email)-1)) {
printf ("YES\n");
} else {
printf ("NO\n");
}
}
return 0;
}