【问题标题】:How to find decoding length of RLE encoded string如何找到 RLE 编码字符串的解码长度
【发布时间】:2018-03-10 07:40:18
【问题描述】:

我是堆栈溢出的新手,所以如果我缺乏某些习惯,我深表歉意。我现在正在使用java,目前正在尝试从RLE格式解码字符串时找到它的长度。例如,“20A6B2C”的长度为 28(20+6+2)。我已经知道如何识别字符串中的单个数字以打印“2062”,但无法识别如何将“20”组合为一个数字或如何按原样添加所有数字。我当前的代码如下。谢谢! (我很抱歉,但总的来说我对编码很陌生。)

public class RLEtrial {
public static void main(String[] args) {

    String rleString = "20A6B2C";

    if (rleString == null || rleString.isEmpty()) System.out.print("");

    StringBuilder sb = new StringBuilder();
    boolean found = false;
    int findDecodeLength = 0;
    for (char c : rleString.toCharArray()) {
        if (Character.isDigit(c)) {
            sb.append(c);
            found = true;
        }
    }
    System.out.print(sb.toString());
}

}

【问题讨论】:

  • 如果要重复的字符是数字,这种“编码”会发生什么?

标签: java string decode decoding


【解决方案1】:

你需要正则表达式。 \\d 用于查找数字;在这种情况下,+ 符号是 repetition 运算符。

String DIGIT_REGEX = "\\d+"; // minimum 1 digit number
Pattern pattern = Pattern.compile(DIGIT_REGEX);
Matcher matcher = pattern.matcher("20A6B2C");
int count = 0;
while(matcher.find()) 
    count += Integer.parseInt(matcher.group(0)); // group 0 is entire pattern (in this case entire number)

System.out.println(count);

【讨论】:

  • 很抱歉,您能解释一下 Pattern 和 Matcher 函数吗?
  • @MissyAggravation 来自 Oracle Java Doc :“正则表达式的编译表示。必须首先将正则表达式指定为字符串,然后将其编译为此类的实例。然后可以将生成的模式用于创建一个 Matcher 对象,该对象可以将任意字符序列与正则表达式进行匹配。”看到这个link
猜你喜欢
  • 2014-04-27
  • 1970-01-01
  • 2013-01-08
  • 1970-01-01
  • 2013-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-16
相关资源
最近更新 更多