第一個只出現(xiàn)一次的字符
一個字符串中,查找其中第一個只出現(xiàn)一次的字符。
這里建設(shè)這個字符串中的字符可以使英文大小寫字符也可以是數(shù)字字符。
http://www.shnenglu.com/jake1036/archive/2011/05/17/146542.html
解決方案是:
用 map 記錄每個字符的出現(xiàn)次數(shù),以及第一次出現(xiàn)的索引。
然后遍歷 map ,找到出現(xiàn) 1 次且索引最小的那個字符。
1 #include <iostream>
2 #include <string>
3 #include <map>
4 using namespace std;
5
6 char findHeadOnce(const string& s)
7 {
8 map<char, int> times;
9 map<char, int> 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<char, int>::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 閱讀(305)
評論(0) 編輯 收藏 引用