Solution 17: 字符串中只出现一次的字符

问题描述

在一个字符串中找到第一个只出现一次的字符。如输入字符串"abbc",应该输出字符'a'。

 

程序

public class FirstCharacter {
	// Time/Space: O(n)
	public char findFirstAppearChar(String s) {
		if (s == null || s.length() == 0) {
			return ' ';
		}

		HashMap<Character, Integer> map = new HashMap<Character, Integer>();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (!map.containsKey(c)) {
				map.put(c, 1);
			} else {
				map.put(c, map.get(c) + 1);
			}
		}

		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (map.get(c) == 1) {
				return c;
			}
		}

		return ' ';
	}

	// Time: O(n^2)
	public char findFirstAppearCharNaive(String s) {
		if (s == null || s.length() == 0) {
			return ' ';
		}

		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			boolean flag = true;
			for (int j = i + 1; j < s.length(); j++) {
				if (s.charAt(j) == c) {
					flag = false;
					break;
				}
			}
			if (flag) {
				return c;
			}
		}
		
		return ' ';
	}
}

 

posted @ 2015-07-03 10:26  Chapter  阅读(155)  评论(0编辑  收藏  举报