|
2 | 2 |
|
3 | 3 | import org.junit.Test; |
4 | 4 |
|
| 5 | +import java.util.HashMap; |
| 6 | +import java.util.Map; |
| 7 | + |
5 | 8 | import static org.hamcrest.CoreMatchers.is; |
6 | 9 | import static org.junit.Assert.assertThat; |
7 | 10 |
|
8 | 11 | public class CharacterCompressWithLength { |
9 | 12 |
|
| 13 | + /* |
| 14 | + TASK |
| 15 | + 주어진 문자열을 길이와 함께 적어주면서 압축을 한다. |
| 16 | + */ |
| 17 | + |
10 | 18 | @Test |
11 | 19 | public void test() { |
12 | | - assertThat("", is(testFunction())); |
| 20 | + assertThat(null, is(RunLengthCompress_USE_HASHMAP(null))); |
| 21 | + assertThat("a3b3c3", is(RunLengthCompress_USE_HASHMAP("aaabbbccc"))); |
| 22 | + assertThat("a3b3c4", is(RunLengthCompress_USE_HASHMAP("aabbacbccc"))); |
| 23 | + |
| 24 | + assertThat("a3b3c3", is(RunLengthCompress("aaabbbccc"))); |
13 | 25 | } |
14 | 26 |
|
15 | | - public String testFunction() { |
16 | | - return ""; |
| 27 | + private String RunLengthCompress_USE_HASHMAP(String str) { |
| 28 | + if (str == null) return null; |
| 29 | + |
| 30 | + Map<Character, Integer> charCounter = new HashMap<>(str.length()); |
| 31 | + |
| 32 | + for (char c : str.toCharArray()) { |
| 33 | + if (charCounter.containsKey(c)) { |
| 34 | + charCounter.put(c, charCounter.get(c) + 1); |
| 35 | + } else { |
| 36 | + charCounter.put(c, 1); |
| 37 | + } |
| 38 | + } |
| 39 | + StringBuilder sb = new StringBuilder(); |
| 40 | + charCounter.forEach((chr, count) -> sb.append(chr + count.toString())); |
| 41 | + return sb.toString(); |
| 42 | + } |
| 43 | + |
| 44 | + private String RunLengthCompress(String str) { |
| 45 | + if (str == null) return null; |
| 46 | + |
| 47 | + char[] ca = str.toCharArray(); |
| 48 | + String result = ""; |
| 49 | + int count = 1; |
| 50 | + char prev = ca[0]; |
| 51 | + |
| 52 | + for (int i = 1; i < ca.length; i++) { |
| 53 | + if (prev == ca[i]) { |
| 54 | + count++; |
| 55 | + } else { |
| 56 | + result = result + prev + count; |
| 57 | + count = 1; |
| 58 | + prev = ca[i]; |
| 59 | + } |
| 60 | + } |
| 61 | + result = result + prev + count; |
| 62 | + return result; |
17 | 63 | } |
18 | 64 | } |
0 commit comments