-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path443.cpp
81 lines (78 loc) · 1.11 KB
/
443.cpp
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
class Solution
{
public:
int compress(vector<char> &chars)
{
int w = 0;
for (int i = 0, j = 0; i < chars.size(); j = i)
{
while (++i < chars.size() && chars[i] == chars[i - 1]);
int k = i - j;
chars[w++] = chars[j];
if (k>1)
{
int start= w;
while (k)
{
chars[w++] = k%10+'0';
k/=10;
}
for (int end = w-1;start <end ; )
{
swap(chars[start++],chars[end--]);
}
}
}
return w;
}
};
class Solution
{
public:
int compress(vector<char> &chars)
{
if (chars.size() <= 1)
{
return chars.size();
}
char pre = chars[0];
int count = 1;
int j = 0;
for (int i = 1; i < chars.size(); i++)
{
if (chars[i] == pre)
{
count++;
} else
{
if (count > 1)
{
chars[j++] = pre;
auto tmp = to_string(count);
for (auto x: tmp)
{
chars[j++] = x;
}
} else
{
chars[j++] = pre;
}
pre = chars[i];
count = 1;
}
}
if (count > 1)
{
chars[j++] = pre;
auto tmp = to_string(count);
for (auto x: tmp)
{
chars[j++] = x;
}
} else
{
chars[j++] = pre;
}
return j;
}
};