1、按特定顺序输出压缩
输入一段字符串,把相同的字符按出现顺序,归在一起,并压缩。
例如:
输入:SamSameCome
输出:
SSaammmeeCo
S2a2m3e2C1o1
【难度系数】 ▲ ▲ ▲ ▲
【分析】
【代码】
#include <stdio.h>
#include <string.h>
int main(void)
{
char ch[100];
char str[100];
char s;
int i = 0;
int j = 0;
int count = 1;
int k = 0;
scanf("%s", ch);
for(i = 0; i < strlen(ch); i++)
{
if(ch[i] != ' ')
{
s = ch[i];
for(j = 0; j < strlen(ch); j ++)
{
if(s == ch[j])
{
str[k] = ch[j];
k++;
ch[j] = ' ';
}
}
}
}
printf("%s\n", str);
for(i = 0; i < strlen(str); i++)
{
if(str[i] == str[i + 1])
{
count ++;
}
else
{
printf("%c%d", str[i], count);
count = 1;
}
}
printf("\n");
return 0;
}
2、IP地址判断是否合法
输入一个IP地址,判断时候ip地址合法
ip地址由4位0-255组成 中间使用 . 隔开
合法的ip地址是:
21.45.34.112 是合法的
第一位不能为全0
0.45.34.112 是不合法的
每一位不能超过255
【代码】
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char ip[20] = {};
int i = 0, j = 0;
int num[4] = {};
scanf("%[^\n]", ip);
char *sep = ".";
char *p = strtok(ip, sep);
while(p != NULL)
{
num[i ++] = atoi(p);
p = strtok(NULL, sep);
}
if(num[0] == 0 || num[0] >255 || num[1] > 255
|| num[2] > 255 || num[3] > 255)
printf("NO\n");
else
printf("YES\n");
return 0;
}
3、字符串压缩
字符串原地压缩。题目描述:“eeeeeaaaff" 压缩为 "e5a3f2"。
字符串压缩算法,把s字符串压缩处理后结果保存在res中
比如:
输入
aaaaeefggg
输出为
a4e2f1g3
输入
hhfhhhhff
输出为
h2f1h4h2
【代码】
#include <stdio.h>
#include <string.h>
int main(void)
{
char ch[100];
int i = 0;
int count = 1;
scanf("%s", ch);
for(i = 0; i < strlen(ch); i++)
{
if(ch[i] == ch[i + 1])
{
count ++;
}
else
{
printf("%c%d", ch[i], count);
count = 1;
}
}
return 0;
}
4、字符串解压
字符串原地压缩。题目描述:"e5a3f2" 解压缩为 “eeeeeaaaff"。
字符串压缩算法,把s字符串压缩处理后结果保存在res中
比如:
输入
a4e2f1g3
输出为
aaaaeefggg
输入
h2f1h4h2
输出为
hhfhhhhff
【代码】
#include <stdio.h>
#include <string.h>
int main(void)
{
char ch[100];
char s[100];
int i = 0, j = 0;
int num = 0;
scanf("%s", ch);
for(i = 0; i < strlen(ch); i++)
{
if(ch[i] >= 'a' && ch[i] <= 'z')
{
if(ch[i + 1] >= '0' && ch[i + 1] <= '9')
{
if(ch[i + 2] >= '0' && ch[i + 2] <= '9')
{
num = (ch[i + 1] - 48) * 10 + (ch[i + 2] - 48);
}
else
num = ch[i + 1] - 48;
}
for(j = 0; j < num ; j++)
{
printf("%c", ch[i]);
}
}
}
printf("\n");
return 0;
}
5、字符串排序
输入一个字符串,然后返回连续最大的字符串
比如demo
1,3,3,3,4,4,4,4,4,0,0,0,4,4,4,4
,此例中由5个连续的4为最大连续子串,返回结果为44444.
1,3,3,3,4,4,4,4,4,0,0,0,0,0,0,5,5,5,5 返回44444;
1,3,3,3,5,5,5,5,5,4,4,4,4,4,0,0,0,0,0,0,4,4,4,4},返回55555;
这是公司OC面试题
【代码】