Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- Medium
- Easy
- Bit
- Subset
- 카카오
- stack
- sorting
- bst
- Math
- LinkedList
- Linked List
- 스택
- Bubble Sort
- tree
- kakao
- list
- 리스트
- 2019 카카오
- 오픈 채팅방
- 순회
- 정렬
- binary search tree
- 완전검색
- leetcode
- traversal
- 트리
- 공채
- 배열
Archives
- Today
- Total
미리수얌 블로그
Leetcode: String Compression 본문
String Compression
주어진 char 배열을 in-place 로 compress 하고 그 길이를 return 하라
하지만 compress 됬을때 더 길어진다면 그냥 그대로 놔둬라
예: [a, a] => [a, 2], [a, b, c, c, d, d, d, a] => [a, b, c, 2, d, 3, a]
이건 쉬운 문제지만 실수를 많이 할 수 있는 문제입니다.
count 를 리셋을 하지 않거나 잘 못 세는 경우가 있습니다.
public int compress(char[] chars) {
char prev = chars[0];
int count = 0;
int cInd = 0;
for (char c: chars) {
if (prev == c) {
count++;
} else {
// print to array
cInd = add(chars, cInd, count, prev);
prev = c;
count = 1;
}
}
// check last
cInd = add(chars, cInd, count, prev);
return cInd;
}
private int add(char[] chars, int index, int count, char c) {
chars[index++] = c;
if (count > 1) {
String strCount = String.valueOf(count);
for (int i = 0; i < strCount.length(); ++i) {
chars[index++] = strCount.charAt(i);
}
}
return index;
}
'코딩문제풀이 > Leetcode' 카테고리의 다른 글
Leetcode: Set Mismatch (0) | 2018.10.05 |
---|---|
Leetcode: Diameter of Binary Tree (0) | 2018.09.29 |
Leetcode: Assign Cookies (0) | 2018.09.29 |
LeetCode: Kth Smallest Element in a BST (0) | 2018.09.29 |
Leetcode: Reverse Words in a String III (0) | 2018.09.29 |
Comments