查找第一个只出现一次的字符

在一个字符串中找到第一个只出现一次的字符。如输入adaccbeff,则输出d。

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 
 5 char find(const string & s1)
 6 {
 7     int hash[26] = {0};
 8     for(int i = 0; i < s1.size(); i++)
 9         hash[s1[i]-'a']++;
10     
11     int i;
12     for(i = 0; i < s1.size(); i++)      //use string travel the hashtable to find the first character in string.
13     {
14         if(hash[s1[i]-'a'] == 1)
15             return s1[i];
16     }
17     if(i == s1.size())
18         return '#';     //cannot find
19 }
20 
21 int main(int argc, char **argv)
22 {
23     string s1("adaccbef");
24     char c = find(s1);
25 
26     cout << c << endl;
27     return 0;
28 }

 

 

posted @ 2012-10-08 10:07  dandingyy  阅读(317)  评论(0)    收藏  举报