Skip to content
本页目录

50-第一个只出现一次的字符

题目描述

https://leetcode.cn/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof

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

示例 1:

输入:s = "abaccdeff"
输出:'b'

示例 2:

输入:s = "" 
输出:' '

限制:

  • 0 <= s 的长度 <= 50000

思路分析

遍历字符串,加入字典表,最后遍历字典表,发现第一个数量为1的字符串,就输出 如果Hash表的key不是按序号排列的,我们重新遍历原字符串,遇到第一个hash表中储存的值是1的,就返回

实现代码

csharp
public class Solution {
    public char FirstUniqChar(string s) {
        if(s == ""){
            return ' ';
        }
        Dictionary<char,int> dict = new Dictionary<char,int>();
        for(int i=0; i<s.Length; i++){
            if(!dict.ContainsKey(s[i])){
                dict.Add(s[i],1);
            }
            else{
                dict[s[i]]++;
            }
        }
        foreach(char key in dict.Keys){
            if(dict[key] == 1){
                return key;
            }
        }
        return ' ';
    }
}

Released under the MIT License.