Table of contents
Sword Pointer Offer 50. The first character that appears only once
Sword Pointer Offer 50. The first character that appears only once
Find the first character that occurs only once in the string s. If not, return a single space. s contains only lowercase letters.
Example 1:
Input: s = "abaccdeff"
Output: 'b'
Example 2:Input: s = ""
Output: ' 'Source: LeetCode
Link: https://leetcode.cn/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof
train of thought
Create an array of judges
Because only lowercase letters are included, the maximum is 26 bits , and the number of the position represented by the subscript will increase by 1 every time the letter appears (both from
0), so the number of the position represented by the subscript is 1, which means that the character appears once and only added once
the code
char firstUniqChar(char* s)
{
int len = strlen(s);
int i = 0;
int judge[26] = {0};
for(i = 0; i < len; i++)
{
judge[s[i] - 'a']++;//只包含小写字母,所以最多就是26位,该字母每出现一次该下标所代表的位置的数就加1(都从0 开始的),所以该下标所代表的位置的数得1,那就表明该字符就出现了一次,只加了一遍
}
for(i = 0; i < len; i++)
{
if(judge[s[i] - 'a'] == 1)
{
return s[i];
}
}
return ' ';
}