《剑指offer》面试题35:第一个只出现一次的字符

题目:在字符串中找出第一个只出现一次的字符。如输入“abaccdeff”,则输出'b'。

思路:用哈希表记录每个char出现的次数。顺序哈希表用 LinkedHashMap。

public char FirstNotRepeatChar(String str) {
	HashMap<Character, Integer> map = new LinkedHashMap<Character, Integer>();
	char[] cs = str.toCharArray();
	for (int i=0; i<cs.length; i++) {
		if (map.containsKey(cs[i]))
			map.put(cs[i], map.get(cs[i])+1);
		else
			map.put(cs[i], 1);
	}
	for (Entry<Character, Integer> entry : map.entrySet()) {
		if (entry.getValue() == 1)
			return entry.getKey();
	}
	return '\0';
}

猜你喜欢

转载自blog.csdn.net/qq_25024883/article/details/80353791