只允许遍历一遍字符串,找出字符串中第一个只出现一次的字符
来源:互联网 发布:网络飚车游戏 编辑:程序博客网 时间:2024/05/01 12:52
find the first unique character in a string and you can just traverse this string only one time. if there is no such character, just return '#' and '#' will not appear in the string, else return the character you find.
for example: "aAbBABac", return 'b', and to "aBBa" return '#' as the final result.
大家熟知的,以往我们找一个字符串中第一个只出现一次的字符的时候都允许重新遍历字符串,解决的思路是建立一个hash表,hash[256](256个字符),遍历一遍字符串,记录每个字符出现的次数,然后在重新遍历字符串,查看每个字符出现的次数,如果出现的次数为1,则打印出此字符,遍历停止。 然而,当只要求遍历一遍字符串的时候,只能得到每个字符出现的次数,不能得到字符原来在字符串中的排列顺序。只要能想到这一点,就能够解决问题了。再重新设定一个order数组来记录字符出现的次序,然后遍历次序数组,取出第几次出现的是哪个字符,然后在到hash表中找它出现的次数,如果次数为1,那么就找到符合要求的字符串了。给出代码:
- #include<stdio.h>
- #include<string.h>
- char getUniqueCharacter(char *s) {
- int order[256] = {0};
- int counter[256] = {0};
- int i = 0;
- char temp;
- char *p = s;
- while(*p) {
- temp = *p;
- if(counter[temp] == 0) { //找出第一次出现的字符
- order[i++] = temp;
- }
- counter[temp]++;
- p++;
- }
- int j;
- for(j = 0; j < 256; j++) {
- if(order[j] != 0) {
- if(counter[order[j]] == 1) {
- temp = order[j];
- break;
- }
- }
- }
- if(j >= 256) {
- return '#';
- } else {
- return temp;
- }
- }
- void main() {
- char s[] = "aAbBABac";
- int n = strlen(s);
- char result = getUniqueCharacter(s);
- printf("%c\n", result);
- getchar();
- }
- 只允许遍历一遍字符串,找出字符串中第一个只出现一次的字符
- 只允许遍历一遍字符串,找出字符串中第一个只出现一次的字符
- 只允许遍历一遍字符串,找出字符串中第一个只出现一次的字符
- 找出字符串中只出现一次的第一个字符
- 找出字符串中第一个只出现一次的字符
- 找出字符串中第一个只出现一次的字符
- 找出字符串中第一个只出现一次的字符
- 找出字符串中第一个只出现一次的字符
- 找出字符串中第一个只出现一次的字符
- 找出字符串中第一个只出现一次的字符
- 找出字符串中第一个只出现一次的字符
- 找出字符串中第一个只出现一次的字符
- 找出字符串中第一个只出现一次的字符
- 找出字符串中第一个只出现一次的字符
- 找出字符串中第一个只出现一次的字符
- 找出字符串中第一个只出现一次的字符
- 找出字符串中第一个只出现一次的字符
- 找出字符串中第一个只出现一次的字符
- hdu 1124 Factorial
- mysql触发器的作用及语法
- 跟ini文件相关的api
- Lua初学
- openam + opendj 安装
- 只允许遍历一遍字符串,找出字符串中第一个只出现一次的字符
- 一个测试电池状态的actiivity
- 【Android基础入门〖14〗】SharedPreferences
- Poj1149 PIGS (经典网络流)
- Sprite Kit 高级场景处理
- 探索推荐引擎内部的秘密,第 3 部分: 深入推荐引擎相关算法 - 聚类
- HDU2795 Billboard
- “黑马程序员“宣传语有奖大征集
- JAVA集合