问题描述
方法:
public static int noOfLetters (String str)
我得到一个字符串,需要返回字符串中唯一字母的数量,大写和小写字母被视为相等,但您不能使用小写字母进行转换,反之亦然。我尝试了很多东西。这是我能编写的最好的代码: 例如:"cd$aD" 将返回 3
public static int noOfLetters(String str) {
char[] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
int count = 0;
int j = 0;
for(int i=0;i<str.length();i++) {
if(str.charat(i) != alphabet[j])
j++;
count++;
}
return count;
解决方法
我建议您枚举字符并将它们放在不区分大小写的地图中。
在循环结束时,您应该获取键集合大小以获取唯一字母的数量。
此处 https://www.baeldung.com/java-map-with-case-insensitive-keys 是有关如何使用不区分大小写地图的教程。 .
,你可以用
str.chars().filter(ch -> (ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122)).map(ch -> ch >= 97? ch-32 : ch).distinct().count();
您首先过滤掉与字母不同的所有字符,然后将所有字符都转换为大写,但如果不允许使用 toLowercase 或 toUppercase 方法
,您可以使用 Set<Character>
来添加您看到的每个字母字符:
要了解这个技巧,您可以访问:ASCII Table
public static int noOfLetters(String str) {
List<Character> alphabet = Arrays.asList('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
Set<Character> uniqueAlphabetSeen = new HashSet<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (alphabet.contains(c)){
uniqueAlphabetSeen.add(c);
}
else if(c >= 'A' && c <= 'Z'){
uniqueAlphabetSeen.add((char) (c -'A' + 'a'));
}
}
return uniqueAlphabetSeen.size();
}
输入:
System.out.println(noOfLetters("cd$aD"));
输出:
3
,
我认为您应该能够通过在循环中为位于 'A'
和 'Z'
之间的所有字符添加一个条件来实现,您可以通过从 {{1} 中减去它来将其转换为小写}:
'A'
我使用此代码对其进行了测试:
public static int noOfLetters(String str) {
Set<Character> distinctChars = new HashSet<>();
for (int i = 0; i < str.length(); i++) {
boolean isUpperCaseChar = str.charAt(i) >= 'A' && str.charAt(i) <= 'Z';
boolean isLowerCaseChar = str.charAt(i) >= 'a' && str.charAt(i) <= 'z';
if (isUpperCaseChar || isLowerCaseChar) {
char convertedLowerCaseChar = str.charAt(i);
if (isUpperCaseChar) {
convertedLowerCaseChar = (char) (str.charAt(i) - 'A' + 'a');
}
distinctChars.add(convertedLowerCaseChar);
}
}
return distinctChars.size();
}
它打印以下内容:
System.out.println(noOfLetters("rohankumar"));
System.out.println(noOfLetters("rohankumarROHAN"));
System.out.println(noOfLetters("rohankumarROHAN-$"));
System.out.println(noOfLetters("cd$aD"));