这是我曾经的一道面试题:
1.双向链表如何循环,如何插入一条数据?
2.一个字符串如何用最简单的方法查出重复的字母?
例如:String str = “agdbadbjja”
最优时间复杂度:
private static void test() {
String str = "agdbadbjja";
Map<Object,Integer> maps = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
char charAt = str.charAt(i);
if (maps.get(charAt) != null) {
Integer integer = maps.get(charAt);
maps.put(charAt, ++integer);
}else{
maps.put(charAt, 1);
}
}
Set<Object> keySet = maps.keySet();
for (Object string : keySet) {
Integer integer = maps.get(string);
System.out.println("key: " + string + " " + "value: " + integer);
}
}
打印结果:
key: a value: 3
key: b value: 2
key: d value: 2
key: g value: 1
key: j value: 2
去重:
/**
* 去重
*/
private static void demo(){
String str = "agdbadbjja";
StringBuffer strb = new StringBuffer();
List lists = new ArrayList<>();
for (int i = 0; i < str.length(); i++) {
if (!lists.contains(str.charAt(i))) {
lists.add(str.charAt(i));
strb.append(str.charAt(i));
}
}
System.out.println(strb.toString());
}