💬 Info
- 난이도 : Medium
- 문제 링크 : https://leetcode.com/problems/string-compression
- 풀이 링크 : LeetCode/Medium/String Compression.java
Given an array of characters chars
, compress it using the following algorithm:
Begin with an empty string s
. For each group of consecutive repeating characters in chars
:
If the group's length is 1
, append the character to s
.
Otherwise, append the character followed by the group's length.
The compressed string s
should not be returned separately, but instead, be stored in the input character array chars
. Note that group lengths that are 10
or longer will be split into multiple characters in chars
.
After you are done modifying the input array, return the new length of the array.
You must write an algorithm that uses only constant extra space.
chars[i]
is a lowercase English letter, uppercase English letter, digit, or symbol.풀이 시간 : 12분
class Solution {
public int compress(char[] chars) {
int idx = 0, cnt = 1;
for (int i = 1; i <= chars.length; i++) {
if (i < chars.length && chars[i] == chars[i - 1]) {
cnt++;
} else {
chars[idx++] = chars[i - 1];
if (cnt > 1) {
for (char c : String.valueOf(cnt).toCharArray()) {
chars[idx++] = c;
}
}
cnt = 1;
}
}
return idx;
}
}