给出一个字符串,找出其中只出现一次且位置最靠前的那个字符

 1 #include <iostream>
 2 #include <string.h>
 3 using namespace std;
 4 char findChar(const char *str)
 5 {
 6     int count[26] = {0};
 7     int index[26] = {0};
 8     unsigned int i;
 9     int pos;
10     for(i = 0;i < strlen(str);i++)
11     {
12         count[str[i]-'a']++;//计数
13         if(index[str[i]-'a'] == 0)
14         {
15             index[str[i]-'a']=i;//标记第一次出现的位置,即当第二次出现的时候,index[]的值已经更新了
16         }
17         //cout<<str[i]<<"--->"<<index[str[i]-'a']<<endl;
18     }
19     pos = strlen(str);
20     for(i = 0;i < 26;i++)
21     {
22         if(count[i] == 1)
23         {
24             if(index[i] != -1 && index[i]< pos)
25             {
26                 pos = index[i];
27             }
28         }
29     }
30     if(pos < strlen(str))
31         return str[pos];
32 }
33 int main()
34 {
35     char str[] = "iamsuperdemonandastudent";
36     cout<<findChar(str)<<endl;
37 }
View Code
原文地址:https://www.cnblogs.com/sxmcACM/p/4495476.html