力扣题:字符的统计-11.25

力扣题-11.25

[力扣刷题攻略] Re:从零开始的力扣刷题生活

力扣题1:387. 字符串中的第一个唯一字符

解题思想:直接遍历即可

力扣题:字符的统计-11.25_第1张图片

class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        char_count = {}
        for i in range(len(s)):
            if s[i] in char_count:
                char_count[s[i]] += 1
            else:
                char_count[s[i]] = 1
        for i in range(len(s)):
            if s[i] in char_count and char_count[s[i]]==1:
                return i
        return -1
class Solution {
public:
    int firstUniqChar(string s) {
        std::unordered_map<char, int> char_count;
        for (char c : s) {
            if (char_count.find(c) != char_count.end()) {
                char_count[c] += 1;
            } else {
                char_count[c] = 1;
            }
        }
        for (int i = 0; i < s.length(); ++i) {
            if (char_count.find(s[i]) != char_count.end() && char_count[s[i]] == 1) {
                return i;
            }
        }
        return -1;
    }
};

你可能感兴趣的:(leetcode,算法,职场和发展)