String
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 524288/524288 K (Java/Others)
Problem Description
You hava a non-empty string which consists of lowercase English letters and may contain at most one '?'. Let's choose non-empty substring G from S (it can be G = S). A substring of a string is a continuous subsequence of the string. if G contains '?' then '?' can be deleted or replaced by one of lowercase english letters. After that if each letter occurs even number of times in G then G is a good substring. Find number of all good substrings.
Input
The input consists of an integer T, followed by T lines, each containing a non-empty string. The length of the string doesn't exceed 20000.
[Technical Specification]
1 <= T <= 100
[Technical Specification]
1 <= T <= 100
Output
For each test case, print a single integer which is the number of good substrings of a given string.
Sample Input
3 abc?ca aabbcc aaaaa
Sample Output
7 6 6HintGood substrings of "abc?ca": "?", "c?", "?c", "c?c", "bc?c", "c?ca", "abc?ca"
题意:给一个由小写字母组成的字符串,里面最多有一个问号‘?’,问有多少个这样的连续字串:
1、字串中的每个字母出现的次数为偶数次
2、?可以代表其中一个字母,也可以删去
题解:本题使用状态压缩 + map + 位运算。
使用状态压缩存储每个位置的状态,需要用到二进制位运算,如果一个字母出现的次数为奇数次,则相应位数为1。由于2^26太大,无法开数组,所以使用map来存储和查找。总的时间复杂度为nlogn
具体见代码:
#include <cstdio>
#include <map>
#include <cstring>
using namespace std;
#define N 20005
map<int, int> mp1, mp2;
map<int, int>::iterator it;
char str[N];
int ans;
void solve(map<int, int> &m1, map<int, int> &m2){
for(it = m1.begin(); it != m1.end(); it++){
int j = it->first, k = it->second;
for(int i = 0; i < 26; i++){//遍历?代表的字母
int q = j ^ (1<<i);
if(m2.find(q) != m2.end())
ans += k * m2[q];
}
ans += k * m2[j]; //?直接去掉的情况
}
}
int main(){
int t;
scanf("%d", &t);
while(t--){
scanf("%s", str);
if(!mp1.empty())mp1.clear();
if(!mp2.empty())mp2.clear();
int len = strlen(str);
int pos = -1; //?的位置
ans = 0; //最终结果
for(int i = 0; i < len; i ++)
if(str[i] == '?')
pos = i;
if(pos != -1) ans++;//只有一个?时,将这个?删掉,也算一种情况
int p = 0;
for(int i = pos - 1; i >= 0; i--){
p = p ^ (1<<(str[i] - 'a'));//p一直和下一个元素异或
if(p == 0) ans ++; //如果异或为0,那么此时就是偶数,结果+1
ans += mp1[p]; //如果之前出现过p,那么现在的p和之前的p异或,结果为0即偶数
mp1[p]++; //p这种情况再+1
}
p = 0;
for(int i = pos + 1; i < len; i++){
p = p ^ (1<<(str[i] - 'a'));
if(p == 0) ans ++;
ans += mp2[p];
mp2[p]++;
}
if(pos != -1){
for(it = mp1.begin(); it != mp1.end(); it++){
int j = it->first;
int k = it->second;
if((j & (j - 1)) == 0)//当只有一位是1时,才可以用?来抵消
ans += k;
}
for(it = mp2.begin(); it != mp2.end(); it++){
int j = it->first;
int k = it->second;
if((j & (j - 1)) == 0)
ans += k;
}
if(mp1.size() < mp2.size())solve(mp1, mp2);//遍历小的map,搜索大的map
else solve(mp2, mp1);
}
printf("%d\n", ans);
}
return 0;
}