题目:在字符串中找出第一个只出现一次的字符。
代码如下:
package demo;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
* 第1个只出现1次的字符
*
* 记录法
*
* @author xiangdonglee
*
*/
public class Test35 {
public static char firstNotRepeatingChar(String s) {
if (s == null || s.length() < 1) {
throw new IllegalArgumentException("Arg should not be null or empty!");
}
Map<Character, Integer> map = new LinkedHashMap<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (map.containsKey(c)) {
map.put(c, -2);
} else {
map.put(c, i);
}
}
Set<Map.Entry<Character, Integer>> entrySet = map.entrySet();
// 记录只出现一次的字符的索引
int index = Integer.MAX_VALUE;
// 记录只出现一次的字符
char result = '\0';
for (Map.Entry<Character, Integer> entry : entrySet) {
if (entry.getValue() >= 0 && entry.getValue() < index) {
index = entry.getValue();
result = entry.getKey();
}
}
return result;
}
public static void main(String[] args) {
System.out.println("google:" + firstNotRepeatingChar("google"));
System.out.println("aabccdbd:" + firstNotRepeatingChar("aabccdbd:"));
System.out.println("abcdefg:" + firstNotRepeatingChar("abcdefg"));
System.out.println("gfedcba:" + firstNotRepeatingChar("gfedcba"));
System.out.println("zgfedcba:" + firstNotRepeatingChar("zgfedcba"));
}
}
运行结果
网友评论