考实现能力 O(n) time O(1) space
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Solution { public: int compress(vector<char>& chars) { int n = chars.size(), res = 0; for (int i = 0, j = 1; i < n; i = j) { while (j < n && chars[j] == chars[i]) { ++j; } chars[res++] = chars[i]; if (i + 1 == j) continue; for (char c : to_string(j - i)) { chars[res++] = c; } } return res; } };
|
用write read anchor来控制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public: int compress(vector<char>& chars) { int n = chars.size(); int w = 0, a = 0; for (int r = 0; r < n; ++r) { if (r + 1 == n || chars[r + 1] != chars[r]) { chars[w++] = chars[a]; if (r > a) { for (char c : to_string(r + 1 - a)) { chars[w++] = c; } } a = r + 1; } } return w; } };
|
O(n) time O(1) space
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public: int compress(vector<char>& chars) { int n = chars.size(); int i = 0; for (int j = i; j < n;) { int cnt = 0; for (; j < n && chars[j] == chars[i]; ++j, ++cnt); if (cnt > 1) { for (char c : to_string(cnt)) { chars[++i] = c; } } ++i; chars[i] = chars[j]; } return i; } };
|