posts - 183,  comments - 10,  trackbacks - 0

第一个只出现一次的字符

一个字符串中,查找其中第一个只出现一次的字符。
这里建设这个字符串中的字符可以使英文大小写字符也可以是数字字符。

http://www.cppblog.com/jake1036/archive/2011/05/17/146542.html

解决方案是:
用 map 记录每个字符的出现次数,以及第一次出现的索引。
然后遍历 map ,找到出现 1 次且索引最小的那个字符。

 1 #include <iostream>
 2 #include <string>
 3 #include <map>
 4 using namespace std;
 5 
 6 char findHeadOnce(const string& s)
 7 {
 8     map<charint> times;
 9     map<charint> indexes;
10     for (string::size_type i = 0; i != s.size(); ++i)
11     {
12         ++times[s[i]];
13         if (times[s[i]] == 1)
14         {
15             indexes[s[i]] = i;
16         }
17     }
18     int idx = s.size();
19     for (map<charint>::const_iterator cit = indexes.begin(); cit != indexes.end(); ++cit)
20     {
21         if (times[cit->first] == 1 && idx > cit->second)
22         {
23             idx = cit->second;
24         }
25     }
26     if (idx < s.size())
27     {
28         return s[idx];
29     }
30     else
31     {
32         return '*';
33     }
34 }
35 
36 int main()
37 {
38     string s;
39     while (cin >> s)
40     {
41         cout << findHeadOnce(s) << endl;
42     }
43 }

 


posted on 2011-07-22 16:21 unixfy 阅读(296) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理