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

来源:互联网 发布:fanuc数控仿真软件 编辑:程序博客网 时间:2024/06/14 15:20

问题

题目:[剑指offer-第一个只出现一次的字符]

思路

哈希的思路。
但是要小心一点的是,看下面注释,如果要全部置0,那么对于第一个数字,它保存的位置就是0,此时应该是无效的。但是,这是一个有效的位置。

代码

class Solution {public:    int FirstNotRepeatingChar(string str) {        int sz = str.size();        if(!sz) return -1;        int hash[128];        memset( hash, -1, sizeof(hash) );// memset( hash, 0, sizeof(hash) ) error        for(int i = 0; i < sz; ++i){            char key = str[i];            if( -1 == hash[key] ) hash[key] = i;            else hash[key] = -2;        }        int ret = INT_MAX;        for(int i = 0; i < 128; ++i){            if( hash[i] != -1 && hash[i] != -2 )                ret = min( ret, hash[i] );         }        return ret;    }};
原创粉丝点击