카테고리 없음
string compression
fw93
2018. 3. 22. 22:07
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 | #include "stdafx.h" #include <iostream> #include <cstdio> #include <string> #include <vector> using namespace std; void compress2(string & data) { int count = 1; char target = data[0]; string res = ""; for (int i = 1; i <= data.size(); i++) { if (i!=data.size() & data[i] == target) { count++; } else { res.push_back(target); if (i != data.size()) { target = data[i]; } vector<int> tmp; while (count != 0) { tmp.insert(tmp.begin(), (count % 10)); count /= 10; } for (int j = 0; j < tmp.size(); j++) { res.push_back(tmp.at(j)+'0'); } count = 1; } } if (data.size() > res.size()) { data = res; } } void compress(string & data) { // time complexity : O(N), space complexity : O(1) int original = data.size(); int count = 1; char target = data[0]; int i = 1; int flag = 0; while (i != data.size()) { if (target == data[i]) { count++; i++; } else { target = data[i]; for (int j = 0; j < count - 1; j++) { data.erase(data.begin() + i - 1); i--; } int c = 0; while (count != 0) { data.insert(data.begin() + i, (count % 10) + '0'); count /= 10; c++; } count = 1; i = i + c + 1; } } for (int j = 0; j < count - 1; j++) { data.erase(data.begin() + i - 1); i--; } int c = 0; while (count != 0) { data.insert(data.begin() + i, (count % 10) + '0'); count /= 10; c++; } if (data.size() < original) { return; } else { int i = 0; int cnt; char target; while (i != data.size()) { target = data[i]; cnt = 0; i++; int tmp[100]; int z = 0; memset(tmp, 0, sizeof(int) * 100); while (data[i] >= '0'&&data[i] < '9') { tmp[z] = data[i] - '0'; data.erase(data.begin() + i); z++; } for (int k = z; k > 0; k--) { cnt += tmp[z-k] * pow(10, z - 1); } for (int k = 0; k < cnt - 1; k++) { data.insert(data.begin() + i, target); i++; } } } } int main() { string data = "aaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbccccccccccccccddddddddddddddeeeeeeeeeeeeeeeeeeeeeeeeeasdqdfhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh"; compress2(data); cout << data << endl; while (1) {} } | cs |