【发布时间】:2014-07-08 15:18:06
【问题描述】:
我必须编写代码来计算字符串中有多少个唯一字母: 例如
"aabbcdefff"
这将返回 6,因为字符串中有 6 个不同的字母。目前我有代码:
String letters = ("aabbcdefff");
char temp = ' ';
for (int i = 0; i < letters.length(); i++){
temp = inp.charAt(i);
if (temp != ' ') { //doesnt count spaces as letters
alphabetSize = alphabetSize+1;
for (int j = 0; j < inp.length(); j++){
tempInp = tempInp.replace(temp,' ');
}
}
}
这段代码的想法是,当检测到一个字母时,它应该用空格替换它的所有实例。然而,当我运行这段代码时,它只是给了我字符串的长度。我究竟做错了什么?还有其他更优雅的方法吗?
感谢您的帮助。
【问题讨论】:
-
如果您想要唯一性,请使用“集合”