样本输入
4
abcd
azazaz
abbzbba
flkjdh
样本输出
4
21
22
0
C++程序:
#define ll long long
char s[1000010];
int main()
{
int t;
cin>>t;
char x;
scanf("%c",&x);
while(t--)
{
scanf("%s",s);
int l=-1;
int len=strlen(&s[0]);
ll ans=0;
for(int i=0;s[i]!='\0';i++)
{
if(s[i]=='a' || s[i]=='z')
{
ans+=((i-l)*(len-i));
l=i;
}
}
cout<<ans<<endl;
}
}
Ruby 中的程序:
n = gets.chomp.to_i
ans = []
for x in 0..n-1
str1 = gets.chomp
l = str1.size
count = 0
i = 0
le = -1
str1.each_char do |cha|
if(cha == 'a' || cha == 'z')
count += (i-le)*(l-i)
le = i
end
i += 1
end
ans[x] = count
end
puts ans
在考虑更长的字符串时,Ruby 比 C++ 慢 15 倍。为什么?