题目1199:找位置
/*********************************
* 日期:2013-2-19
* 作者:SJF0115
* 题号: 九度OJ 题目1199:找位置
* 来源:http://ac.jobdu.com/problem.php?pid=1199
* 结果:AC
* 来源:2005年华中科技大学计算机保研机试真题
* 总结:
**********************************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct Character{
char c;//字符
int count;//个数
int location[101];//数组中位置
int flag;//标记已输出
}Character;
int main()
{
int i,index,j;
char str[101];
Character c[150];
while(gets(str)){
//初始化
for(i = 0;i < 150;i++){
c[i].count = 0;
c[i].flag = 0;
}
//统计字符个数,字符位置
for(i = 0;i < strlen(str);i++){
c[str[i]].c = str[i];
index = c[str[i]].count;
c[str[i]].location[index] = i;
c[str[i]].count++;
}
for(i = 0;i < strlen(str);i++){
//有重复的字符且没有输出过
index = str[i];
if(c[index].count > 1 && c[index].flag == 0){
//输出重复字符
for(j = 0;j < c[index].count-1;j++){
printf("%c:%d,",str[i],c[index].location[j]);
}
printf("%c:%d\n",str[i],c[index].location[j]);
//标记已读
c[index].flag = 1;
}
}
}
return 0;
}
另一种方法:
/*********************************
* 日期:2013-2-19
* 作者:SJF0115
* 题号: 九度OJ 题目1199:找位置
* 来源:http://ac.jobdu.com/problem.php?pid=1199
* 结果:AC
* 来源:2005年华中科技大学计算机保研机试真题
* 总结:从数组头开始遍历,如果有重复字符且没有输出便输出
**********************************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int i,j,len,first;
char str[101];
while(gets(str)){
int flag[150] = {0};
len = strlen(str);
for(i = 0;i < len;i++){
first = 1;
//该字符已输出
if(flag[str[i]]){
continue;
}
for(j = i+1;j < len;j++){
if(str[i] == str[j]){
//第一个数
if(first){
first = 0;
printf("%c:%d",str[i],i);
}
printf(",%c:%d",str[j],j);
//标记该字符已输出
flag[str[i]] = 1;
}
}//for
//如果该字符已输出最后结尾换行
if(flag[str[i]]){
printf("\n");
}
}
}
return 0;
}