玩命加载中 . . .

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


LeetCode 387. First Unique Character in a String

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

Example 1:

Input: s = "leetcode"
Output: 0

Example 2:

Input: s = "loveleetcode"
Output: 2

method

哈希表存储每个字符的出现次数,返回第一个出现次数为1的字符下标

int firstUniqChar(string s) {
    int hash[26] = {0};
    for (int i = 0; i < s.size(); i++) {
        hash[s[i] - 'a']++;
    }
    for (int i = 0; i < s.size(); i++) {
        if (hash[s[i] - 'a'] == 1) return i;
    }
    return -1;
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录