在字符串中对字符进行分组的更简洁方法

问题描述

我正在用 Java 练习罗马数字加法。根据消除减法符号、组合然后分组为更高值的等价物的规则,“IV”+“IV”将如下所示:

  1. “IV”+“IV”
  2. "IIII" + "IIII"
  3. “IIIIIIIII”
  4. “VIII”(将 5 I 的“IIIIII”转换为“V”)

我使用下面的代码将 8 个 I 分为“IIIIII”和“III”。然后我可以使用 Map(未显示)将“IIIIII”转换为“V”。下面的分组代码可以用Stream方法编写吗?

     private String[] group(String sortedRawSum) {
        List<String> groupedChars = new ArrayList<>();
        int i=0;
        while (i+5 < sortedRawSum.length()) {
            if ( sortedRawSum.substring(i,i+5).equals("IIIII") ) {
                groupedChars.add("IIIII");
                i += 5;
                continue;
            }
            i++;
        }
        if (i < sortedRawSum.length()) {
            groupedChars.add(sortedRawSum.substring(i));
        }

        return groupedChars.toArray(new String[0]);
    }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)