字符串中第一个只出现一次的字符

87 阅读1分钟

字符串中第一个只出现一次的字符

在字符串中找出第一个只出现一次的字符。

如输入"abaccdeff",则输出b。

如果字符串中不存在只出现一次的字符,返回#字符。

样例:
输入:"abaccdeff"
输出:'b'

遍历

时间复杂度O(n)

class Solution {
    public char firstNotRepeatingChar(String s) {
        Map<Character,Integer> map = new HashMap();
        char[] strs = s.toCharArray();
        for(char ch : strs){
            if(map.get(ch) != null){
                map.put(ch,map.get(ch) + 1);
            }else{
                map.put(ch,1);
            }
        }
        for(char ch : strs){
            if(map.get(ch) == 1){
                return ch;
            }
        }
        return '#';
    }
}