这是一道大模拟。
题意简述
给定一个字符串 ,求满足形如“电子邮箱”的子串数量。
题目做法
首先,先找一个特殊字符@,稍后作为扩展的字符。
由@先向左扩展子串。查找仅含有字母、数字以及下划线的子串。但是注意:只有首位为字母的才能对答案贡献。
int l=i-1,r=i+1;
int times1=0,times2=0;
while((isalpha(s[l]) || isdigit(s[l]) || s[l]=='_') && l>=0){
if(isalpha(s[l]))times1++;
l--;
}接下来向右查找字符.,如果中途@到.的子串有除小写字母和数字以外的字符,贡献为 ,直接退出。
while((isalpha(s[r]) || isdigit(s[r]) || s[r]=='.') && r<=SIZE){
if(s[r]=='.'){
flg=true;
r++;
break;
}
r++;
}
if(!flg)continue;接下来判断.后面是否合法。查找到除小写字符就退出。
while(isalpha(s[r]) && r<=SIZE+1){
r++;
times2++;
}最后对答案能产生 的贡献。
特判
如果你 WA on #26,那么你可以看看下面这句话。
helloworld@.中@和.相连是不合法的。
代码
下面放出全部代码。
#include<bits/stdc++.h>
using namespace std;
string s;
int SIZE;
int ans;
signed main(){
getline(cin,s);
SIZE=s.size();
s=" "+s;
for(int i=1;i<=SIZE;i++){
if(s[i]!='@')continue;
int l=i-1,r=i+1;
int times1=0,times2=0;
while((isalpha(s[l]) || isdigit(s[l]) || s[l]=='_') && l>=0){
if(isalpha(s[l]))times1++;
l--;
}
bool flg=false;
if(s[r]=='.')continue;
while((isalpha(s[r]) || isdigit(s[r]) || s[r]=='.') && r<=SIZE){
if(s[r]=='.'){
flg=true;
r++;
break;
}
r++;
}
if(!flg)continue;
while(isalpha(s[r]) && r<=SIZE+1){
r++;
times2++;
}
ans+=times1*times2;
}
cout<<ans;
return 0;
}