第一个只出现一次的字符(Python and C++解法)

题目:

在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。

示例:

s = "abaccdeff"
返回 "b"

s = ""
返回 " "

限制:

0 <= s 的长度 <= 50000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof

思路:

  在C++解法中,使用unordered_map统计字符出现的次数。需要注意:由于unordered_map的底层是哈希表,元素的顺序是打乱的,因此不能使用iterator找第一个元素。

  在Python解法中,由于给定字符串中只包含小写字母,而小写字母只有26个,因此可以定义一个大小为26的整数数组来保存字符串中出现的各个小写字母的个数,最后再遍历一遍给定字符串找到第一个出现一次的字符并返回,以数组映射的方法实现哈希表。需要注意:在计算数组下标时,Python不允许两个str直接相减,需要使用python的ord()函数,其返回值是字符对应的ascii码,可以通过该方法来实现两个字符之间的减法运算。

Python解法:

 1 class Solution:
 2     def firstUniqChar(self, s: str) -> str:
 3         res = ' '
 4         charArray = [0] * 26
 5         for i in range(len(s)):  # 'a'的下标为0,'b'的下标为1......
 6             charToNum = ord(s[i]) - ord('a')  # 字符间的ASCII码值相减
 7             charArray[charToNum] += 1
 8         
 9         for i in range(len(s)):  # 从数组中查找符合次数要求的字符
10             charToNum = ord(s[i]) - ord('a')
11             if charArray[charToNum] == 1:
12                 res = s[i]
13                 break
14         return res

C++解法:

 1 class Solution {
 2 public:
 3     char firstUniqChar(string s) {
 4         char res = ' ';  // 如果字符串长度为0,直接返回
 5         unordered_map<char, int> countChar;
 6         for(int i = 0; i < s.size(); i++)  // 往哈希表中添加元素并计数
 7             countChar[s[i]] += 1;
 8         for(int i = 0; i < s.size(); i++)  // 找符合要求的字符
 9             if(countChar[s[i]] == 1) {
10                  res = s[i];
11                  break;
12             }  
13         return res;
14     }
15 };
原文地址:https://www.cnblogs.com/kongzimengzixiaozhuzi/p/13323352.html