题解 | #第一个只出现一次的字符#
第一个只出现一次的字符
https://www.nowcoder.com/practice/1c82e8cf713b4bbeb2a5b31cf5b0417c
第一种: class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param str string字符串 * @return int整型 */ int FirstNotRepeatingChar(string str) { // write code here int cnt[52]={0}; for(int i=0; i<=str.size()-1; i++){ if(str[i]>='a' && str[i] <= 'z'){ cnt[str[i]-97]++; } if(str[i]>='A' && str[i] <= 'Z'){ cnt[26+str[i]-65]++; } } for(int i=0; i<=str.size()-1; i++){ if(cnt[str[i]-97] == 1 || cnt[26+str[i]-65] ==1){ return i; } } return -1; } }; 第二种: class Solution { public: int FirstNotRepeatingChar(string str) { // 使用一个长度为52的数组,前26个存储小写字母的计数,后26个存储大写字母的计数 int cnt[52] = {0}; auto inc_count = [&](char c) { if (c >= 'a' && c <= 'z') cnt[c - 'a']++; else if (c >= 'A' && c <= 'Z') cnt[26 + c - 'A']++; }; auto is_first_not_repeating = [&](char c) { return (c >= 'a' && c <= 'z' && cnt[c - 'a'] == 1) || (c >= 'A' && c <= 'Z' && cnt[26 + c - 'A'] == 1); }; // 遍历字符串,统计字符出现次数 for (char c : str) inc_count(c); // 再次遍历字符串,找到第一个不重复的字符 for (int i = 0; i < str.size(); ++i) { if (is_first_not_repeating(str[i])) return i; } return -1; } };