我想使用哈希表来查找唯一字符,因为它对我来说似乎更有效,例如,哈希表中的 hello 将是 => {h:1,e:1,l:2,o:1} & since value大于 1 则字符串不唯一。我知道我可以用 ascii 方式计算唯一字符,但我想实现哈希表方式。
请注意,我不想要正则表达式实现。
static void findHashUnique(String str)
{
Hashtable<Character, Integer> ht = new Hashtable<Character, Integer>();
for(int i=0;i<str.length();i++)
{
int cnt=1;
if(!ht.containsKey(str.charAt(i)))
{
ht.put(str.charAt(i), cnt);
}
}
System.out.print(ht);
}
我卡在了如何首先初始化哈希表并检查值是否存在然后递增的部分。在 'l' 的情况下,它将递增到 2 而不是 1,因为 key 是相同的。 另外这个解决方案是否有效?
最佳答案
这是我的方法。
String string = "hello";
Hashtable<Character, Integer> map = new Hashtable<>();
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
System.out.println(map);
输出:{e=1, o=1, l=2, h=1}
关于java - 查找字符串是否唯一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23576475/