找出字符串中第一个只出现一次的字符

昨天参加了一次笔试,最后一道题是这样的:找出一个纯字母字符串中第一个只出现一次的字符。

我的思路是这样的,假设该字符串是由纯小写字母组成,则可以定义一个布尔数组,该数组保存每个字符出现次数是否大于 1 的状态。接着遍历字符串,同时利用 ASCII 码对应到布尔数组,判断状态即可。鄙人的 C++ 代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <cassert>
using namespace std;

char FirstAppearOnce(char* str) {
bool moreThanOnce[26] = {false};
for (char* p = str; *p != '\0'; ++p) {
assert((*p >= 'a') && (*p <= 'z'));
char* q;
for (q = p + 1; !moreThanOnce[*p - 'a'] && (*q != '\0'); ++q) {
if (*q == *p) {
moreThanOnce[*p - 'a'] = true;
break;
}
}
if (*q == '\0') {
return *p;
}
}
return 0;
}

int main() {
char* str = "thisisateststring";
cout << FirstAppearOnce(str) << endl;
system("pause");
return 0;
}

如果存在大小 写、符号等情况,则可以为 整个 ASCII 字符创建一个布尔数组(ASCII 有 128 个字符,因此数组可改为  128 个元素 ) 。对上面代码稍稍修改一下,便可以支持所有字符:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;

char FirstAppearOnce(char* str) {
bool moreThanOnce[128] = {false};
for (char* p = str; *p != '\0'; ++p) {
char* q;
for (q = p + 1; !moreThanOnce[*p] && (*q != '\0'); ++q) {
if (*q == *p) {
moreThanOnce[*p] = true;
break;
}
}
if (*q == '\0') {
return *p;
}
}
return 0;
}

int main() {
char* str = "This is a test string.";
cout << FirstAppearOnce(str) << endl;
system("pause");
return 0;
}

欢迎拍砖。

找出字符串中第一个只出现一次的字符

http://whypro.github.io/hexo-blog/2012/10/19/58ffa14619a8/

Author

whypro

Posted on

2012-10-19

Updated on

2022-11-11

Licensed under

Comments

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×