LeetCode 387 字符串中的第一个唯一字符

class Solution {
public:
int firstUniqChar(string s)
{
    int n=s.size();
    int p[256]={0};
//int *p=new int[256];
//memset(p,0,sizeof(p)); for(int i=0; i<n; i++) { p[s[i]]++; } for(int i=0; i<n; i++) { //cout<<p[s[i]]<<endl; if(p[s[i]]==1) { return i; } } return -1; } };

一开始用

int *p=new int[256];

memset(p,0,sizeof(p));

没过,很迷.

后来发现sizeof(p)==4

但是未过样例是61.  62*4=……

其他人的答案:

class Solution {
public:
    int firstUniqChar(string s) {
        vector<int> m(26,0);
        for(auto c : s) {
            ++m[c - 'a'];
        }
        for(auto i = s.cbegin();i != s.cend();++i) {
            if(m[*i - 'a'] == 1) return i - s.cbegin(); 
        }
        return -1;
    }
};

原文地址:https://www.cnblogs.com/azureice/p/leetcode387.html