D. Count Good Substringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".
Given a string, you have to find two values:
- the number of good substrings of even length;
- the number of good substrings of odd length.
InputThe first line of the input contains a single string of length n (1 ≤ n ≤ 105). Each character of the string will be either 'a' or 'b'.
OutputPrint two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.
Sample test(s)inputbb
output1 2
inputbaab
output2 4
inputbabb
output2 5
inputbabaa
output2 7
NoteIn example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.
In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.
In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.
Definitions
A substring s[l, r] (1 ≤ l ≤ r ≤ n) of string s = s1s2... sn is string slsl + 1... sr.
A string s = s1s2... sn is a palindrome if it is equal to string snsn - 1... s1.
这题只需要保存当前位置为止,在奇数位上和偶数位上分别出现了多少次0和1。
从来没有使用过python的二维数组。。。在别人的代码中学习了,不过还是不会用。。
如:
c = [[0 for i in xrange(2)] for i in xrange(2)]
或者:
1 a = {'a' : [0 , 0] , 'b' : [0 , 0]}
Accepted Code:
1 s = list(raw_input());
2 L = len(s);
3 even, odd = 0, 0;
4 ev, od = [0]*2, [0]*2;
5 for i in xrange(1, L+1):
6 t = 0 if s[i-1]=='a' else 1;
7 if i % 2 :
8 od[t] += 1
9 even += ev[t];
10 odd += od[t]
11 else :
12 ev[t] += 1
13 even += od[t]
14 odd += ev[t]
15 print even, odd