您的位置:首页 > 编程语言

微软2014编程之美初赛第二场——题目2 : 字符串压缩

2014-04-20 16:13 441 查看
【来源】

题目2 : 字符串压缩

【分析】

把游程编码恢复为原始字符串,然后得出每一行的字符串的内容,放在一个vector中。用map统计vector中每一行的重复的次数。

比较两个游程编码得到的map是否相同即可。

该算法占用空间太多,小数据AC,大数据MLE了。

【代码】

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <sstream>
using namespace std;

int main()
{
int T;
cin >> T;
for (int c = 0; c < T; ++c){
int L;
cin >> L;
string code1, code2;
cin >> code1 >> code2;
stringstream ss1;
ss1 << code1 + "0A";
stringstream ss2;
ss2 << code2 + "0A";

string raw1 = "";
string raw2 = "";
while(!ss1.eof()){
int freq;
ss1 >> freq;
char c;
ss1 >> c;
if (freq == 0){
break;
}
for (int j = 0; j < freq; ++j){
raw1 += c;
}
}

while (!ss2.eof()){
int freq;
ss2 >> freq;
char c;
ss2 >> c;
if (freq == 0){
break;
}
for (int j = 0; j < freq; ++j){
raw2 += c;
}
}

int lines = raw1.size()/L;
vector<string> lines1, lines2;
map<string, int> map1, map2;
for (int i = 0; i < lines; ++i){
string line = "";
for (int j = 0; j < L; ++j){
line += raw1[i+j*lines];
}
if (map1[line] == 0){
map1[line] = 1;
}
else{
++map1[line];
}
lines1.push_back(line);
}

for (int i = 0; i < lines; ++i){
string line = "";
for (int j = 0; j < L; ++j){
line += raw2[i + j*lines];
}
if (map2[line] == 0){
map2[line] = 1;
}
else{
++map2[line];
}
lines2.push_back(line);
}
int ii;
for (ii = 0; ii < lines; ++ii){
if (map1[lines1[ii]] != map2[lines1[ii]]){

break;
}
}
int jj;
for (jj = 0; jj < lines; ++jj){
if (map1[lines2[jj]] != map2[lines2[jj]]){

break;
}
}

if ((ii == lines) && (jj == lines) && (raw1.size() == raw2.size())){
cout << "Case " << c + 1 << ": Yes" << endl;
}
else{
cout << "Case " << c + 1 << ": No" << endl;
}
}

//system("pause");
return 0;
}

【点评】
字符串处理题。当时想的算法太占用空间了,应该可以利用文本内容只有a-z这26个字符来做文章,比如Hash什么的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  微软 编程之美