【问题标题】:Counting the number of unique letters in a string计算字符串中唯一字母的数量
【发布时间】: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,' ');
        }
      }
    }   

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

感谢您的帮助。

【问题讨论】:

  • 如果您想要唯一性,请使用“集合”

标签: java string letters


【解决方案1】:

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

    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)的运行时间

【讨论】:

    【解决方案2】:

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

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

    string str = "TestTest";
    int cnt = str.ToLower().ToCharArray().Where(w => w != ' ').Distinct().Count();
    

    【讨论】:

    • 问题被标记为 java - 这是 c#。
    【解决方案3】:

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

    long numberOfDistinctChars = s.chars().distinct().count()
    

    【讨论】:

      【解决方案4】:

      您可以使用 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

      谢谢。

      【讨论】:

      • 不应该是Set吗?
      • 很好,我忘了:)
      • 谢谢,但是当我运行“Set set = new HashSet();”行时它给了我错误“未经检查和不安全的操作”,但阅读了一个提出这个问题的线程,看起来我没有做错什么?
      • 您使用的是字符还是字符?使用字符。
      • 我使用了“Set set = new HashSet();”这一行它在“HashSet”上给了我一个红框
      【解决方案5】:

      只要使用 Set 就可以了。

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

      【讨论】:

      • 这比您当前的实现更容易实现,并且时间复杂度更低。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-27
      相关资源
      最近更新 更多