其实写代码很简单,主要是要分析清楚问题的实质,下面几点是至关重要的:
1.如果字符串是奇数长度,最后一个字符永远都保持在最后一位。
2.从0开始,每一对字母不管怎么变换都是挨在一块的,也就是说,str[0]和str[1]、str[2]和str[3]始终是相邻的。
3.如果把上述一对看成一个整体,那么通过有限步数变换,一个字符对可以跑到任何一个位置而不影响其他字符的相对顺序(最后一个位置除外)
有了以上分析,问题就简单了。一个字符串中所有字符对进行排序,然后再对所有字符串进行排序,踢出重复的就可以了。
唉,其实也不难想,但是比赛那会愣是没想出来。。。
下面的代码已经通过了system test
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
class EllysReversals {
public:
int getMin(vector <string>);
};
//adjacent letters will keep adjacent forever
//except last one in odd length case
int EllysReversals::getMin(vector <string> words) {
int len = words.size();
for(int i=0; i<len; i++){
vector<string> v;
int t = words[i].size()/2;
for(int j=0; j<t; j++){
string str = words[i].substr(j*2, 2);
if(str[0] > str[1]){
char tmp = str[0];
str[0] = str[1];
str[1] = tmp;
}
v.push_back(str);
}
sort(v.begin(), v.end());
for(int j=0; j<v.size(); j++){
words[i][j*2] = v[j][0];
words[i][j*2+1] = v[j][1];
}
}
sort(words.begin(), words.end());
int res = 0;
for(int i=1; i<len; i++){
if(words[i] == words[i-1]){
res += 2;
i++;
}
}
res = len-res;
return res;
}
//<%:testing-code%>
//Powered by [KawigiEdit] 2.0!