剑指 Offer 50. 第一个只出现一次的字符

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

示例:

s = “abaccdeff”
返回 “b”

s = “”
返回 " "

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Java

class Solution {
    public char firstUniqChar(String s) {
        if(s.equals("")) return ' ';
        Map<Character,Integer> map=new HashMap<>();
        for(int i=0;i<s.length();i++){
            char c=s.charAt(i);
            if (map.containsKey(c))
                map.put(c,map.get(c)+1);
            else
                map.put(c,1);
        }
        for(int i=0;i<s.length();i++){
            char c=s.charAt(i);
            if(map.get(c)==1){
                return c;
            }

        }
        return ' ';
    }
}

优化

class Solution {
    public char firstUniqChar(String s) {
         if(s.equals("")) return ' ';
        int [] hash=new int[26];
        for(int i=0;i<s.length();i++) {
            hash[s.charAt(i)-'a']++;
        }
        for(int i=0;i<s.length();i++){
            if(hash[s.charAt(i)-'a']==1)
                return  s.charAt(i);

        }
        return ' ';
    }
}
上一篇:310. Android 输入手机号码自动空格


下一篇:leetcode 65 有效数字