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
- 친절한SQL튜닝
- 페이징
- 알파회계
- 자바편
- 자료구조와 함께 배우는 알고리즘 입문
- 자료구조와함께배우는알고리즘입문
- 처음 만나는 AI 수학 with Python
- /etc/network/interfaces
- 네트워크 설정
- d
- 리눅스
- 스프링부트핵심가이드
- 이터레이터
- iterator
- GIT
- 코드로배우는스프링웹프로젝트
- 구멍가게코딩단
- 처음 만나는 AI수학 with Python
- 목록처리
- 서버설정
- 코드로배우는스프링부트웹프로젝트
- baeldung
- network configuration
- 선형대수
- resttemplate
- 데비안
- Kernighan의 C언어 프로그래밍
- ㅒ
- 스프링 시큐리티
- 티스토리 쿠키 삭제
Archives
- Today
- Total
bright jazz music
443. String Compression 본문
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.
Note: The characters in the array beyond the returned length do not matter and should be ignored.
Example 1:
Input: chars = ["a","a","b","b","c","c","c"]
Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
Explanation: The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3".
Example 2:
Input: chars = ["a"]
Output: Return 1, and the first character of the input array should be: ["a"]
Explanation: The only group is "a", which remains uncompressed since it's a single character.
Example 3:
Input: chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]
Output: Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].
Explanation: The groups are "a" and "bbbbbbbbbbbb". This compresses to "ab12".
Constraints:
1 <= chars.length <= 2000
chars[i] is a lowercase English letter, uppercase English letter, digit, or symbol.
function compress(chars: string[]): number {
// write pointer
let write = 0;
// read pointer
let i = 0;
while(i < chars.length) {
// 현재 문자
const char = chars[i];
let count = 0;
// 연속된 같은 문자 카운트
// 배열 길이보다 적고, 같은 값인 경우 카운트가 올라감
while(i < chars.length && chars[i] === char) {
count++;
i++
}
// 끝까지 읽었거나 값이 달라져서 위의 반복문이 끝났음
// Now that we've finished reading this group, let's write
// 후위 증가 연산자라서 먼저 write의 현재 값을 배열의 인덱스로 사용해서 값을 할당하고 그 다음 ++ 됨.
// 최초라면 0에 할당되고 자동으로 write가 1이 됨
chars[write++] = char;
// If count > 1, write the count as well
if(count > 1) {
const countStr = count.toString();
// Iterate and attach stringified digits
for(const digit of countStr) {
// 여기도 마찬가지. 먼저 기존의 write값을 인덱스로 사용해서 값을 할당하고 그 다음 ++ 함.
chars[write++] = digit
}
}
}
return write;
}
// function compress(chars: string[]): number {
// // 객체에 속성으로 집어넣어서 카운팅하자
// // 그리고 차례로 다시 배열에 집어 넣는다.
// // 이 때, 만약 해당 문자의 개수가 1이라면 그냥 넣고, 1 초과 10미만이라면 숫자를 문자로 만들어서 넣는다.
// // 10 이상이라면 자릿수대로 쪼개서 넣는다.
// const charMap = new Map<string, number>();
// chars.forEach((char) => charMap.set(char, (charMap.get(char) || 0) + 1))
// console.log(charMap)
// // return [] as string[]
// // return <string, number>[]
// };
좋은 질문이에요! 제가 판단한 근거들:
1. 함수 시그니처 분석
typescriptfunction compress(chars: string[]): number
배열을 받는데 배열을 반환하지 않고 number를 반환 → in-place 수정 암시
LeetCode에서 이런 패턴은 "원본 배열 수정 + 유효 길이 반환"을 의미해요
2. 문제 이름 추정
함수명이 compress → 압축 문제
LeetCode 443번 "String Compression"과 시그니처가 정확히 일치
3. 일반적인 압축 알고리즘 특성
압축은 보통 연속된 중복을 처리 (Run-Length Encoding)
Map으로 전체 카운팅하면 순서가 깨지고 연속성을 잃어요
실제로 확인하는 방법:
문제를 제대로 파악하려면:
typescript// 예제 입력/출력을 보면 명확해져요
Input: ["a","a","b","b","c","c","c"]
Output: 6 // 길이를 반환
// chars는 이렇게 변해야 함:
["a","2","b","2","c","3"]
핵심 힌트들:
✅ 반환 타입이 number → 길이 반환
✅ 배열을 인자로 받지만 새 배열을 안 만듦 → in-place
✅ 압축 = 연속된 문자 처리
제가 문제 설명을 직접 본 게 아니라, 이런 시그니처 패턴과 일반적인 압축 알고리즘 지식으로 추론한 거예요.
혹시 문제 설명이나 예제가 있다면 확인해보시겠어요? 제 추측이 맞는지 확인할 수 있을 거예요! 🙂'Algorithm Practice > LeetCode' 카테고리의 다른 글
| 283. Move Zeroes (0) | 2026.01.21 |
|---|---|
| 334. Increasing Triplet Subsequence (0) | 2026.01.17 |
| 238. Product of Array Except Self (0) | 2026.01.16 |
| 151. Reverse Words in a String (0) | 2026.01.15 |
| 345. Reverse Vowels of a String (0) | 2026.01.14 |
Comments