题目描述
题目一:字符串中第一个只出现一次的字符。
在字符串中找出第一个只出现一次的字符。如,输入"abaccdeff",则输出’b’。
实现
方法:
1)扫描一个,和后面的每个字符比较,时间复杂度O(
n
2
n^2
n2)
2)哈希:扫描一遍,更新出现次数,时间复杂度O(n),空间复杂度O(1)。
更新一个字符出现的次数O(1)
查询一个字符出现的次数O(1)
// 实现一个简单的哈希表的功能,时间复杂度O(n)
public class C50_string_FirstNotRepeatingChar {
static char firstNotRepeatingChar(String str) {
if (str == null || str.length()==0) {
return ' ';
}
// 字符(char)是一个长度为8的数据类型,因此共有256种可能
// 创建大小为256,以字符ASCII码为键值的哈希表
int[] hash = new int[256];
// 统计出现次数,存在数组中
for (int i = 0; i < str.length(); i++) {
int temp = str.charAt(i);
hash[temp]++;
}
// 顺序遍历,将出现的次数为1的字符打印出来
for (int i = 0; i < str.length(); i++) {
char temp = str.charAt(i);
if (hash[temp] == 1) {
return temp;
}
}
return ' ';
}
}
Test
public static void main(String[] args) {
String str = "abaccdeff";
System.out.println(firstNotRepeatingChar(str));
}