[Jobdu] 题目1283:第一个只出现一次的字符
- 题目描述:
-
在一个字符串(1<=字符串长度<=10000,全部由大写字母组成)中找到第一个只出现一次的字符。
- 输入:
-
输入有多组数据
每一组输入一个字符串。
- 输出:
-
输出第一个只出现一次的字符下标,没有只出现一次的字符则输出-1。
- 样例输入:
-
ABACCDEFF AA
- 样例输出:
-
1 -1
分析:
这道面试题对时间复杂度的要求是O(n)。如果按照普通的遍历数组的方法,时间复杂度为O(n2),那么思考一下如何用O(n)的算法解决此问题。利用HashTable的思想,就可以做到O(n),由于ASCII中有256个字符,为0-255,用一个字节表示。将数组map[256]作为哈希表,数组下标为字符,数组中的值对应字符出现的次数。第一遍扫描字符串,确定每个字符出现的次数。第二遍扫描字符串,确定第一个只出现一次的字符。
总结:这类题目很具有代表性,在字符串处理的问题中,经常采用哈希表的方法来解决问题,因为散列查找是线性查找,所以往往可以得到最佳的时间复杂度O(n),除了寻找字符串中出现特定次数的字符外,删除字符串中重复出现的字符或者指定的字符,这类问题也可以采用哈希表的方法来解决。
代码:
1 #include <cstdio> 2 #include <cstring> 3 4 #define MAXSIZE 10001 5 6 int main() { 7 char str[MAXSIZE]; 8 while (scanf("%s", str) != EOF) { 9 int map[256] = {0}; 10 const char *p = str; 11 12 while (*p != '\0') 13 map[*p++]++; 14 15 int i; 16 for (i = 0; i < strlen(str); i++) { 17 if (map[str[i]] == 1) 18 break; 19 } 20 if (i != strlen(str)) { 21 printf("%d\n", i); 22 } else { 23 printf("-1\n"); 24 }
25 } 26 27 return 0; 28 }
扩展:
1.实现一个函数,给定两个字符串str1和str2,将字符串str1中出现在str2中的字符删除掉,例如str1="Less is more",str2="sor",返回"Le i me"
2.实现一个函数,删除字符串中所有重复出现的字符,例如"google",返回"gole"
1 char *deleteCharacters(char *p1, char *p2) { 2 int map[256] = {0}; 3 while (*p2 != '\0') 4 map[*p2++]++; 5 6 char *newStr = (char *) malloc(sizeof(char) * MAXSIZE); 7 char *p = newStr; 8 while (*p1 != '\0') { 9 if (map[*p1] == 0) { 10 *p++ = *p1++; 11 } else { 12 p1++; 13 } 14 } 15 16 return newStr; 17 }
还有一个留作练习,自己实现。