public static char getFirstNoRepeatChar(String str) {
// 使用LinkedHashMap可以记住元素的插入顺序
Map<Character, Integer> map = new LinkedHashMap<Character,Integer>(
str.length());
for (char c :str.toCharArray()) {
// 以字符作为k 出现的个数作为值
map.put(c,map.containsKey(c) ? map.get(c) + 1 : 1);
}
// 遍历Map 找到第一个值为1的就是找的结果
for(Entry<Character, Integer> entry : map.entrySet()) {
if(entry.getValue() == 1)
returnentry.getKey();
}
throw newRuntimeException("没有找到相关的字符");
}
本文介绍了一种使用Java编程语言的方法来查找给定字符串中的第一个非重复字符。通过运用LinkedHashMap保持字符出现的顺序及计数,该算法能够高效地找出目标字符。
1548

被折叠的 条评论
为什么被折叠?



