반응형
Recent Posts
Notice
Recent Comments
Link
250x250
«   2025/06   »
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
Archives
Today
Total
관리 메뉴

지식창고

[Java] LeetCode 443. String Compression 본문

Algorithm/Leetcode

[Java] LeetCode 443. String Compression

junz 2023. 3. 2. 19:33
728x90
반응형

[Java] LeetCode 443. String Compression

 

문   제 : 

문자로 이루어진 문자 배열 chars가 주어진다.

이 문자열을 압축해야 한다.

반복해서 나온 문자를 문자+나온횟수 로 압축한다.

1번만 나왔다면 나온횟수를 적지 않는다.

그리고 최종적으로 몇 글자로 압축됐는지 리턴해라.

 

Constraint

{ 1 <= chars.length <= 2000 }

 

 

Example )

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".

//////////////////////////////////////////////////////////

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.

//////////////////////////////////////////////////////////

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".

 



접   근 : 

Two Pointer 로 접근했다.


해   결 : 

배열을 돌면서 각 문자가 몇 번 나왔는지 센다.

만약 해당 문자가 한 번 이상 나왔다면 숫자도 문자뒤에 써줘야 하므로 나온 횟수를 문자열로 바꾼뒤, 문자 배열로 치환해서 문자 뒤에 붙여준다.

그리고 최종적으로 그 문자열의 마지막 인덱스를 리턴해준다.


결   과  :

class Solution {
  public int compress(char[] chars) {
    int ans = 0;

   
    for (int i = 0; i < chars.length;) {
      final char letter = chars[i];
      int count = 0;

      while (i < chars.length && chars[i] == letter) { // 글자 몇 개 나왔는지 셈
        ++count;
        ++i;
      }
      
      chars[ans++] = letter; // 맨 앞 글자 - 지금 세고 있는 글자로 

      if (count > 1) { // 1보다 크면 숫자도 뒤에 써줘야함
        for (final char c : String.valueOf(count).toCharArray()) {
          chars[ans++] = c;
        }
      }

    }
    return ans;
  }
}
728x90
반응형
Comments