(字符串):
在一個字符串中找到第一個只出現一次的字符。如輸入abaccdeff,則輸出b。
先遍歷一遍,統計各個字符的出現次數。在遍歷一遍,若當前字符的出現次數為 1,則返回。若不存在這樣的字符則返回 0。
1 #include <iostream>
2 #include <string>
3 using namespace std;
4
5 char solve(const string& s)
6 {
7 static int times[26] = {0};
8 memset(times, 0, sizeof (times));
9 for (size_t i = 0; i < s.size(); ++i)
10 {
11 ++times[s[i] - 'a'];
12 }
13 for (size_t i = 0; i < s.size(); ++i)
14 {
15 if (times[s[i] - 'a'] == 1)
16 {
17 return s[i];
18 }
19 }
20 return 0;
21 }
22
23 int main()
24 {
25 string s = "abaccdeff";
26 cout << solve(s) << endl;
27 return 0;
28 }
posted on 2011-05-15 23:44
unixfy 閱讀(688)
評論(0) 編輯 收藏 引用