【问题标题】:Is there a more efficient way to count the number of times each consecutive letter appears in a string? (java)有没有更有效的方法来计算每个连续字母出现在字符串中的次数? (爪哇)
【发布时间】:2019-11-14 22:21:38
【问题描述】:

我正在制作一种方法,它采用指定的字符串并计算每个连续字母出现的次数。
例如: 编码(“aabbcc”); 应该给出输出 2 2 2,因为有 2 个字母按顺序出现

我的代码是:

for(int i=0;i<word.length()-1;i++) {
    int count=1;

    if(i!=word.length()-1) {
        //System.out.println(word.charAt(i));
        //System.out.println(word.charAt(i+1));
        try {
            while(word.charAt(i)==word.charAt(i+1)) {
                count++;
                i++;
            }
        } catch (Exception e) {}

        System.out.print(count+" ");
    }
}

但它一直给我一个IndexOutOfBoundsException,所以我只是添加了一个 try and catch 块,但我知道有更好的方法

【问题讨论】:

  • 这条线catch (Exception e) {} 通常不是一件好事。我会删除该 try catch 并使用适当的应用程序流程修复任何异常。

标签: java string algorithm count


【解决方案1】:

不要像 word.charAt(i)==word.charAt(i+1) 这样向前看,因为这会给你错误。相反,检查索引 i 处的字母是否与前一次迭代中的字母相同 - 如果是,则增加计数器。

【讨论】:

    【解决方案2】:

    另一种方法是使用正则表达式。

    String str = "aabbccxa";
    String result = Pattern.compile("(?<=(.))(?!\\1)")
                           .splitAsStream(str)
                           .map(e -> String.valueOf(e.length()))
                           .collect(Collectors.joining(" "));
    System.out.println(result);
    

    它是如何工作的:

    • 在相同字符组中拆分字符串
    • 将每个组映射到其长度
    • 收集使用空间作为分隔符

    我认为这是否比其他答案更好是一个品味问题。比简单的循环更有效?我认为这也取决于输入。

    【讨论】:

      【解决方案3】:

      欢迎来到 SO。一般来说,如果您收到异常,您需要找出原因而不是添加捕获。

      一个更简单的解决方案是:

      Deque<Integer> counts = new LinkedList<>();
      for (int i = 0; i < word.length(); i++) {
          if (i > 0 && word.charAt(i) == word.charAt(i - 1))
              counts.addLast(count.removeLast() + 1);
          else
              counts.addLast(1);
      }
      

      【讨论】:

        【解决方案4】:

        在循环结束时,i+1 超出范围。

        你可以这样计算它们:

        if(i > 0 && word.charAt(i) == word.charAt(i - 1))
        

        【讨论】:

          【解决方案5】:

          您可以在while 循环条件中测试i + 1 是否小于word.length()。您也可以将word.length() 保存到局部变量中。喜欢,

          int len = word.length();
          for (int i = 0; i < len - 1; i++) {
              int count = 1;
              while (i + 1 < len && word.charAt(i) == word.charAt(i + 1)) {
                  count++;
                  i++;
              }
              System.out.print(count + " ");
          }
          

          【讨论】:

            【解决方案6】:
                String str="aabbbccaaaacds";
                boolean flag=false;
                int cnt=1;
                for (int i = 0; i < (str.length()-1); i++) {  // iterate till length -1 as we are using str.charAt(i+1) 
                    if(str.charAt(i)==str.charAt(i+1)) {
                        flag=true; // keep flag as true till matching chars
                        cnt=cnt+1;
                    }
                    else {
                        flag=false; 
                    }
                    if(flag==false && cnt>=2) {
                        System.out.println("char="+str.charAt(i)+", occurance="+cnt);
                        cnt=1;
                    }
                    if(i==(str.length()-2) && flag) { // only used when we are at comparing last two characters
                        System.out.println("char="+str.charAt(i)+", occurance="+cnt);
                    }
            
                }
            

            输出:

            char=a, occurance=2
            char=b, occurance=3
            char=c, occurance=2
            char=a, occurance=4
            

            【讨论】:

              【解决方案7】:

              您可以在地图中收集它们并打印出来。这会打印出与计数匹配的实际字符串,但可以根据需要轻松定制。

                    String str = "aabbbbcccccdddddaaaaz";
              
                    Map<Integer, List<String>> freq = Arrays.stream(
                          str.replaceAll("(([a-z])\\2*)", "$1,").split(",")).filter(
                                a -> a.length() > 1).collect(
                                      Collectors.groupingBy(String::length));
              
                    freq.forEach((k, v) -> System.out.println(k + " : " + v));
              

              打印以下内容。

              2 : [aa]
              4 : [bbbb, aaaa]
              5 : [ccccc, dddd]

              【讨论】:

                猜你喜欢
                • 2016-03-29
                • 1970-01-01
                • 2016-01-23
                • 1970-01-01
                • 2020-07-23
                • 1970-01-01
                • 2021-12-19
                • 2015-12-01
                • 1970-01-01
                相关资源
                最近更新 更多