List<int> intList = [1,2,3,4,5,6];
print(intList); // [1,2,3,4,5,6]
intList.length = 3;
print(intList); // [1,2,3]
이렇게 길이를 지정하면 바로 list가 잘린다.
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.
class Solution {
int compress(List<String> chars) {
int index = 0;
int i = 0;
while(i < chars.length) {
String currentChar = chars[i];
int count = 0;
// 반복되는 캐릭터의 수를 카운트하고 회차를 추가한다.
while(i < chars.length && chars[i] == currentChar) {
i++;
count++;
}
// 반복되는 캐릭터가 끝나면 char의 위치에 캐릭터를 삽입
chars[index] = currentChar;
index++;
// 카운트가 있다면 그 캐릭터의 위치 다음에 숫자를 삽입
if( count > 1) {
for (var s in count.toString().split("")) {
chars[index] = s;
index++;
}
}
}
print("before: $chars");
chars.length = index;
print("after : $chars");
return index;
}
}
Index를 이용해서 list 안의 숫자를 덮어쓰는게 포인트