笔试遇到的题目-------字符串压缩问题
给定一串只含字母的字符串按以下规则进行压缩
压缩1:连续多个重复的字母使用数字加字母
压缩2:压缩后的字符串长度必须小于或等于原字符串长度
方法:通过遍历字符串的长度,然后进行匹配,如果结果相同,那么count+1;
1 #include <iostream> 2 using namespace std; 3 4 int main() 5 { 6 char str[20] ; 7 cin.get(str, 20); 8 int strLength = strlen(str); 9 int count = 1;//记录重复个数 10 int i; 11 for (i = 0; i < strLength; i++) 12 { 13 if (str[i + 1] == str[i]) 14 { 15 count++; 16 } 17 else 18 { 19 if (count == 1) 20 { 21 printf("%c", str[i]); 22 } 23 else 24 { 25 printf("%d%c", count, str[i]); 26 } 27 count = 1;//重置 28 } 29 } 30 system("pause"); 31 return 0; 32 }
该代码会对那种输出字符串有多少个相同的字母有问题,这种方法在以后的时间会更新出来。
 
                    
                
 
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号