剑指offer(19)-第一个只出现一次的字符

来源:互联网 发布:pitstop汉化破解版mac 编辑:程序博客网 时间:2024/04/28 11:45

题目:在一个字符串(1<=字符串长度<=10000,全部由大写字母组成)中找到第一个只出现一次的字符,并返回它的位置.

思路:暴力法很容易想到,复杂度为O(n^2),一种巧妙的方法是把字符看成是整数,将它ASCII码值作为索引记录字符出现的次数,类似与计数排序的思想。返回第一次出现的频数为1的字符对应索引即可。

class Solution {public:    int FirstNotRepeatingChar(string str) {        if (str.size() == 0)            return -1;        const int tablesize = 256;        unsigned int hashTable[tablesize];        int length = str.size();        for (int i = 0;i < tablesize;++i)            hashTable[i] = 0;        int count = 0;        string pHashKey = str;        while (str[count] != '\0')            {            hashTable[pHashKey[count]]++;            count++;        }        pHashKey = str;        count = 0;        while (str[count] != '\0')            {            if (hashTable[pHashKey[count]] == 1)                return count;            count++;        }        return -1;    }};
1 0
原创粉丝点击