该问题要求“实现一种算法来确定字符串是否具有所有唯一字符。
我看到了解决方案,但不太明白。
public boolean isUniqueChars(String str) {
if (str.length() > 256) return false;
boolean[] char_set = new boolean[256];
for (int i = 0; i < str.length(); i++) {
int val = str.charAt(i);
if (char_set[val])
return false;
char_set[val] = true;
}
return true;
}
我们不使用吗parseInt
or (int)
代码前面的转换器? (将要str.charAt[i]
自动更改为int
?)
什么是boolean[] char set=new boolean[256]
意思是?
为什么我们需要设置char_set[val]=true
?
我们还可以使用HashSet
数据结构判断是否string具有java中所有独特的字符。
Set testSet = new HashSet();
for (int i = 0; i < str.length(); i++) {
testSet.add(new Character(str.charAt(i)));
}
if (testSet.size() == str.length()) {
System.out.println("All charcaters are Unique");
} else {
System.out.println("All charcaters are niot unique");
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)