class Solution {
public int compress(char[] chars) {
char current = chars[0];
int count = 1;
int p = 1;
for (int i = 1; i < chars.length; i++) {
if (chars[i] == chars[i-1]) {
count++;
} else {
current = chars[i];
if (count == 1) {
chars[p] = current;
p++;
continue;
} else {
char[] countChar = String.valueOf(count).toCharArray();
for (char c : countChar) {
chars[p] = c;
p++;
}
chars[p] = current;
p++;
}
count = 1;
}
}
if (count != 1) {
char[] countChar = String.valueOf(count).toCharArray();
int j = 0;
for (char c : countChar) {
chars[p] = c;
p++;
}
}
return p;
}
}
복잡한 로직 흐름
중복 코드
// 루프 안
char[] countChar = String.valueOf(count).toCharArray();
// 루프 밖 (마지막 처리)
char[] countChar = String.valueOf(count).toCharArray();
count == 1일 때 비효율
class Solution {
public int compress(char[] chars) {
int write = 0; // 쓰기 위치
int i = 0; // 읽기 위치
while (i < chars.length) {
char current = chars[i];
int count = 0;
// 같은 문자 개수 세기
while (i < chars.length && chars[i] == current) {
i++;
count++;
}
// 문자 쓰기
chars[write++] = current;
// 개수가 2 이상이면 숫자 쓰기
if (count > 1) {
for (char c : String.valueOf(count).toCharArray()) {
chars[write++] = c;
}
}
}
return write;
}
}
class Solution {
public int compress(char[] chars) {
int write = 0;
for (int read = 0; read < chars.length; ) {
char current = chars[read];
int count = 0;
while (read < chars.length && chars[read] == current) {
read++;
count++;
}
chars[write++] = current;
if (count > 1) {
for (char c : Integer.toString(count).toCharArray()) {
chars[write++] = c;
}
}
}
return write;
}
}
| 방법 | 시간 | 공간 | 가독성 |
|---|---|---|---|
| 내 코드 | O(n) | O(1) | 보통 |
| 방법 1 | O(n) | O(1) | 좋음 |
| 방법 2 | O(n) | O(1) | 매우 좋음 |
read: 현재 확인 중인 위치write: 결과를 쓸 위치Run-Length Encoding (RLE)
입력: ['a','a','b','b','c','c','c']
과정: a(2), b(2), c(3)
출력: ['a','2','b','2','c','3']
class Solution {
public int compress(char[] chars) {
int write = 0;
int read = 0;
while (read < chars.length) {
char current = chars[read];
int count = 0;
// 같은 문자 개수 세기
while (read < chars.length && chars[read] == current) {
read++;
count++;
}
// 문자 쓰기
chars[write++] = current;
// 개수가 2 이상이면 숫자 쓰기
if (count > 1) {
for (char c : String.valueOf(count).toCharArray()) {
chars[write++] = c;
}
}
}
return write;
}
}
개선 사항:
#LeetCode #TwoPointer #String #InPlace #RLE #Compression #Medium #StringBuilder