九度 题目1006:ZOJ问题-----------------我没有A掉
我用的算法思想::
记'z'前o的个数为a, 'z'和'j'之间o的个数为b, 'j'之后的o的个数为c.
分析文法可以发现,符合文法的字符串将满足:
1) b != 0
2) a * b = c
我的代码:已经AC掉::::红色的代码是我所不明白的
#include <iostream>
#include <algorithm>
#include<string>
using namespace std;
int main()
{
string str;
while(cin>>str)
{
int i=0,a=0,b=0,c=0;
int count_z=-1,count_j=-1,count_o=-1;
bool flag=false;
for (i=0;i<str.size();i++)
{
if (str[i]=='z' && count_z==-1)
{
count_z=i;
}
else if (str[i]=='j' && count_j==-1)
{
count_j=i-count_z-1;
}
else if (str[i] != 'o')
{
flag = true;
break;
}
}
count_o=str.size()-count_z-count_j-2;
if (flag==false && count_j!=0 && count_z!=-1 && count_j!=-1 && count_o==count_z*count_j)
cout<<"Accepted"<<endl;
else cout<<"Wrong Answer"<<endl;
//str.clear();
}
return 0;
}
我借鉴了一位大神的代码:转载链接http://blog.csdn.net/stephen_wong/article/details/43448777
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
while (cin >> str)
{
int z_index=-1, j_index=-1;
bool more_than_one_z_or_j = false;
for (size_t i = 0; i < str.size(); ++ i)
{
if (str[i]=='z' && z_index==-1)
{
z_index = i;
} else if (str[i]=='j' && j_index==-1)
{
j_index = i;
} else if (str[i] != 'o')
{
more_than_one_z_or_j = true;///这应该是防止zoj 之外的字符
break;
}
}
if (more_than_one_z_or_j == false
&& z_index != -1
&& j_index != -1
&& z_index + 1 < j_index
&& z_index*(j_index-z_index-1) == (str.size()-1-j_index))
{
cout << "Accepted" << endl;
} else
{
cout << "Wrong Answer" << endl;
}
}
return 0;
}