何海涛:《剑指Offer:名企面试官精讲典型编程题》:九度OJ
-
题目描述:http://ac.jobdu.com/problem.php?cid=1039&pid=18
-
在一个字符串(1<=字符串长度<=10000,全部由大写字母组成)中找到第一个只出现一次的字符。
-
输入:
-
输入有多组数据
每一组输入一个字符串。
-
输出:
-
输出第一个只出现一次的字符下标,没有只出现一次的字符则输出-1。
-
样例输入:
-
ABACCDEFF AA
-
样例输出:
-
1 -1
思想:因为只有大写字母,那么设置一个数组吗m[26],是结构体,元素有:字母个数、第一次的下标(在字符串中的位置),扫描完string后,在扫描数组,if 字母个数==1,看看下标是不是比之前的那个小,从而得解!
代码AC:
#include <stdio.h>
#include <string.h>
typedef struct data
{
int first_idx;
int count;
}data;
int main()
{
int i, min = -1;
data d[26];
char str[10001];
while( gets( str ) )
{
for( i = 0; i < 26; i++ )
{
d[i].count = 0;
d[i].first_idx = -1;
}
i = -1;
while( str[++i] )
{
d[str[i]-'A'].count++;
if( d[str[i]-'A'].count == 1 )
{
d[str[i]-'A'].first_idx = i;
}
}
min = -1;
for( i = 0; i < 26; i++ )
{
if( d[i].count == 1 )
{
if( min == -1 )
{
min = d[i].first_idx;
}
else
{
if( min > d[i].first_idx )
{
min = d[i].first_idx;
}
}
}
}
printf("%d\n", min );
}
return 0;
}