From cd8500e6bc72ec21b2e0a2614ab5403678c115ab Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 13 Aug 2024 18:23:30 +0200 Subject: [PATCH] =?UTF-8?q?cs:=20add=20=C2=AB443.=20String=20Compression?= =?UTF-8?q?=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- cs/string-compression.cs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 cs/string-compression.cs diff --git a/cs/string-compression.cs b/cs/string-compression.cs new file mode 100644 index 0000000..06928a6 --- /dev/null +++ b/cs/string-compression.cs @@ -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); + } +}