문제
Given a string word, compress it using the following algorithm:
Begin with an empty string comp. While word is not empty, use the following operation:
Remove a maximum length prefix of word made of a single character c repeating at most 9 times.
Append the length of the prefix followed by c to comp.
Return the string comp.
요약
연속된 문자가 몇개있는지 세되 9개 씩만
풀이
어렵진않다 우선 첫글자를 저장해두고 다음 문자가 같은지 비교후 다르거나 9를 넘는다면 sb에 push해주고 아니면 count ++을 해준다.
코드
class Solution {
public String compressedString(String word) {
StringBuilder sb = new StringBuilder();
char c = word.charAt(0);
int count = 1;
for (int i = 1; i < word.length(); i ++) {
if (c != word.charAt(i) || count == 9) {
sb.append(count);
sb.append(c);
c = word.charAt(i);
count = 1;
continue;
}
count ++;
}
sb.append(count);
sb.append(c);
return sb.toString();
}
}
풀이 시간
5분
체감 난이도
easy
'알고리즘' 카테고리의 다른 글
2024 11 06 3011. Find if Array Can Be Sorted (0) | 2024.11.06 |
---|---|
2024 11 05 2914. Minimum Number of Changes to Make Binary String Beautiful (1) | 2024.11.05 |
2024 11 03 Result796. Rotate String (1) | 2024.11.03 |
2024 11 02 2490. Circular Sentence (0) | 2024.11.02 |
2024 11 04 1957. Delete Characters to Make Fancy String (2) | 2024.11.01 |