"Programming Thinking and Practice" 1044. Data Compression

"Programming Thinking and Practice" 1044. Data Compression

topic

insert image description here
insert image description here

train of thought

Use a structure to store each character and its corresponding number of consecutive occurrences (no more than 255), and traverse the string to determine whether the next character is the same as the previous character.

the code

#include<stdio.h>
#include<string.h>

typedef struct{
    
    int count;char a;}Data;  //字符和对应的个数

int main()
{
    
    
	int T;
	scanf("%d",&T);
	for(int i=0;i<T;i++)
	{
    
    
		char s[501];
		scanf("%s",s);
		Data tab[500];  //最多500个字符
		for(int j=0;j<500;j++)
		{
    
    
			tab[j].count=0;	
		} 
		int k=0;
		for(int j=0;j<strlen(s);j++)
		{
    
    
			tab[k].a=s[j];
			tab[k].count++;
			while(s[j+1]==s[j])    //后一个与前一个比较
			{
    
    
				tab[k].count++;
				j++;
				if(tab[k].count==255)  //不超过255
				{
    
    
					break;
				}
			}
			k++;	
		}
		printf("case #%d:\n",i);
		for(int j=0;j<500;j++)
		{
    
    
			if(tab[j].count!=0)
			{
    
    
				printf("%d%c",tab[j].count,tab[j].a);  //出现次数+对应字符
			}
		}
		printf("\n");
	}	
	return 0;
}

Guess you like

Origin blog.csdn.net/boxueyuki/article/details/130494720