2

我必须编写代码来计算字符串中有多少个唯一字母:例如

"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,' ');
        }
      }
    }   

这段代码的想法是,它应该在检测到一个字母时,用一个空格替换它的所有实例。然而,当我运行这段代码时,它只是给了我字符串的长度。我究竟做错了什么?还有另一种更优雅的方法吗?

谢谢你的帮助。

4

5 回答 5

6

只需使用 Set 就可以了。

循环遍历您的字符串,并将每个字母添加到您的集合中。之后,检查你的集合的长度,然后你就完成了。

于 2014-05-20T11:27:11.997 回答
2

它是带有 Java 8 流式 API 的单线器:

long numberOfDistinctChars = s.chars().distinct().count()
于 2014-05-20T11:39:30.047 回答
1

您可以使用Linq服务轻松找到它。

请添加using System.Linq;命名空间。

string str = "TestTest";
int cnt = str.ToLower().ToCharArray().Where(w => w != ' ').Distinct().Count();
于 2014-05-20T12:08:04.043 回答
0

您可以使用Java 集合 (Set)轻松完成。

Set<Character> result = new HashSet<Character>();

    String letters = ("aabbcdefff");              
       for (int i = 0; i < letters.length(); i++){
          result.add(letters.charAt(i));
        }   

您的最终结果在结果集中,并且始终是唯一的。

参考:http ://docs.oracle.com/javase/7/docs/api/java/util/Set.html

谢谢。

于 2014-05-20T11:32:28.727 回答
0

一种方法是将字符串转换为数组,然后使用以下方法:

    String s = "aabbcdefff";

    char[] charArray = s.toCharArray();

    ArrayList<Character> al = new ArrayList<Character>();


    for(char c : charArray){
        if(al.contains(c)){
            al.remove((Character)c);
        }else{
            al.add(c);
        }
    }

数组列表“al”中留下的都是重复的。这种方法的优点是它有 O(n) 运行时间

于 2014-05-20T13:50:15.703 回答