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; } };

一开始用spa

int *p=new int[256];code

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

没过,很迷.string

后来发现sizeof(p)==4io

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

 

其余人的答案:di

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; } };
相关文章
相关标签/搜索