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

Cracking The Coding Interview 3rd -- 1.5*

2014-01-14 10:30 429 查看
Implement a method to perform basic string compression using the counts of repeated characters. For example, the string "aabcccccaaa" would become a2b1c5a3. If the "compressed" string would not become smaller than the original string, your method
should return the original string.


Analysis: This problem only asks for compressing in such way that we don't need to worry about combining "a2" and "a3" together. As required, it would be pretty straight forward that we simply scan original string and create a new string,
then compare. 

Solution 1:

Scan every character in string and count its occurrences.

Solution 2:

Further compression, combine "a2" and "a3" into "a5", as a result the order of characters will change. In this algorithm, we use an integer array of size 256 to store the counts of each character as discussed in previous questions.

Solution 3 ... 

According to book solution, string concatenation takes much longer time, as a result we should use stringbuffer (Java). I will post c++ version later.

 Header file

#ifndef __QUESTION_1_5_H_CHONG__
#define __QUESTION_1_5_H_CHONG__

#include <string>

using namespace std;

class Question1_5 {
public:
string stringCompression(string target);
string stringCompression_2(string target);
string stringCompression_3(string target);
int run();
};
#endif // __QUESTION_1_5_H_CHONG__


Source file

#include "stdafx.h"
#include "Question1_5.h"
#include <iostream>

using namespace std;

string Question1_5::stringCompression(string target)
{
if (target.size()==0) {
return target;
}

string res = "";  // new string storing results
char c = target[0];   // previous different character
int cnt = 1;    // counts on each character
for (int i=1; i<target.size(); ++i) {
if (target[i]==c) {
cnt++;
}
else {
res += c;
res += char(cnt+'0');
cnt = 1;
c = target[i];
}
}
// The loop always misses the last character in string, so we add them back
res += c;
res += char(cnt+'0');

if (res.size()<target.size()) {
return res;
}
else
return target;
}

// use ASCII 256 array to storage counts on each character
string Question1_5::stringCompression_2(string target)
{
if (target.size()==0) {
return target;
}

string res = "";
int counts[256] = {0};
for (int i=0; i<target.size(); ++i) {
counts[int(target[i])]++;
}
for (int i=0; i<256; ++i) {
if (counts[i]!=0) {
res += char(i);
res += char(counts[i]+'0');
}
}

if (res.size()<target.size()) {
return res;
}
else return target;
}

string Question1_5::stringCompression_3(string target)
{
...
}

int Question1_5::run()
{
// assume there's no spaces in string
string input[] = {"abcdabcd", "aaabbbcccddddaaabbbcccdddd"};
for (int i=0; i<2; ++i) {
cout << input[i] << " after compression_1 is " << stringCompression(input[i])
<< " after compression_2 is " << stringCompression_2(input[i]) << endl;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息