题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).(从0开始计数)
解答
统计每个字符出现的次数,要保持key的插入顺序,使用LinkedHashMap。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| public int FirstNotRepeatingChar(String str) { if (str == null || str.length() == 0) { return -1; } Map<Character, Integer> countMap = new LinkedHashMap<>(); int index = 0; for (char c : str.toCharArray()) { if (countMap.containsKey(c)) { countMap.put(c, -1); } else { countMap.put(c, index); } index++; } index = 0; for (Character character : countMap.keySet()) { int id = countMap.get(character); if (id != -1) { return id; } index++; } return -1; }
|