cs: add «443. String Compression»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
fc92c7a091
commit
cd8500e6bc
1 changed files with 33 additions and 0 deletions
33
cs/string-compression.cs
Normal file
33
cs/string-compression.cs
Normal file
|
@ -0,0 +1,33 @@
|
|||
public class Solution {
|
||||
private static int WriteChar(char[] chars, int start, char c, int count) {
|
||||
chars[start++] = c;
|
||||
if (count == 1) {
|
||||
return start;
|
||||
}
|
||||
|
||||
int digits = 1 + (int)Math.Log10(count);
|
||||
|
||||
start += digits - 1;
|
||||
for (int offset = 0; offset < digits; count /= 10, ++offset) {
|
||||
chars[start - offset] = (char)('0' + (count % 10));
|
||||
}
|
||||
|
||||
return start + 1;
|
||||
}
|
||||
|
||||
public int Compress(char[] chars) {
|
||||
int i = 0;
|
||||
|
||||
var count = 1;
|
||||
for (int j = 1; j < chars.Length; ++j) {
|
||||
if (chars[j] != chars[j - 1]) {
|
||||
i = WriteChar(chars, i, chars[j - 1], count);
|
||||
count = 0;
|
||||
}
|
||||
|
||||
++count;
|
||||
}
|
||||
|
||||
return WriteChar(chars, i, chars.Last(), count);
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue