0

我正在使用 RLE,我正在尝试用 Java 创建一个解压缩程序。我有:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Scanner;

public class Decompress {

    public static String decode(String string) {

        StringBuffer dest = new StringBuffer();
        Pattern pattern = Pattern.compile("[0-9]+|[a-zA-Z]");
        Matcher matcher = pattern.matcher(string);
        while (matcher.find()) {
            int number = Integer.parseInt(matcher.group());
            matcher.find();
            while (number-- != 0) {
                dest.append(matcher.group());
            }
        }
        return dest.toString();   
      }
      public static void main(String[] args) {

          Scanner sc = new Scanner(System.in);
          System.out.print("Enter string: ");
          String string = sc.nextLine();
          String output = "";
          System.out.println(decode(output));
    }
}

但这对我不起作用。我有用户输入,如 a2b3 和输出 aabbb 它不能被硬编码

4

1 回答 1

0

您可能应该([a-zA-Z])([0-9]+)使用正则表达式。这样你就有了正则表达式已经解析的部分。

Pattern pattern = Pattern.compile("([a-zA-Z])(\d+)");
Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
    String letter = matcher.group();
    int number = Integer.parseInt(matcher.group());
    while (number-- != 0) {
        dest.append(letter);
    }
    matcher.find();
}
于 2015-02-04T18:38:47.500 回答