fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. char* rr(const char* s) {
  6. if (*s == '\0') return (char*)s;
  7.  
  8. int len = strlen(s);
  9. char* c = (char*)malloc(2 * len + 1); // 최악의 경우 (문자 + 숫자)
  10. if (!c) return NULL; // 메모리 할당 실패 처리
  11.  
  12. int cnt = 1;
  13. int j = 0;
  14.  
  15. // 문자열 압축 처리
  16. for (int i = 1; i < len; ++i) {
  17. if (s[i] == s[i - 1]) {
  18. cnt++;
  19. } else {
  20. j += sprintf(c + j, "%c%d", s[i - 1], cnt);
  21. cnt = 1;
  22. }
  23. }
  24. j += sprintf(c + j, "%c%d", s[len - 1], cnt);
  25.  
  26. // 압축된 문자열의 길이가 원본 문자열보다 짧으면 압축된 문자열을 반환
  27. if (strlen(c) < len) {
  28. return c;
  29. }
  30.  
  31. // 원본 문자열을 그대로 반환
  32. free(c);
  33. return (char*)s;
  34. }
  35.  
  36. int main() {
  37. char input[1001];
  38. if (scanf("%1000s", input) != 1) {
  39. printf("Input error\n");
  40. return 1; // 입력 오류 처리
  41. }
  42.  
  43. char* result = rr(input);
  44. if (result) {
  45. printf("%s\n", result);
  46. if (result != input) {
  47. free(result); // 동적 메모리 해제
  48. }
  49. } else {
  50. printf("Memory error\n");
  51. }
  52.  
  53. return 0;
  54. }
  55.  
Success #stdin #stdout 0.01s 5292KB
stdin
KKKKKKKKKKKKKKKKKKKKKQWERTYUIOPASDFGKKZXC
stdout
KKKKKKKKKKKKKKKKKKKKKQWERTYUIOPASDFGKKZXC