代码之家  ›  专栏  ›  技术社区  ›  TheFlyBiker 420

如何撤消这种基于正则表达式的压缩?

  •  -2
  • TheFlyBiker 420  · 技术社区  · 6 年前

    我压缩了我的二进制字符串,它输出了3131个1s(111111),它代表了我在这里找到的@tigrang的代码中的字符“p” link .

         public static String compress_string(String inp) {
            String compressed = "";
            Pattern pattern = Pattern.compile("([\\w])\\1*");
            Matcher matcher = pattern.matcher(inp);
            while(matcher.find()) {
               String group = matcher.group();
               if (group.length() > 1) compressed += group.length() + "";
               compressed += group.charAt(0);
            }
            return compressed;
        }
    

    现在我需要解压缩这个字符串“3131”,并使其输出111111。如何在不使用循环的情况下执行此操作? 还有什么方法可以更进一步压缩它,例如:输出61而不是3131?

    1 回复  |  直到 6 年前
        1
  •  1
  •   OldCurmudgeon    6 年前

    比如:

    public static String compress_string(String inp) {
        String compressed = "";
        Pattern pattern = Pattern.compile("([\\w])\\1*");
        Matcher matcher = pattern.matcher(inp);
        while (matcher.find()) {
            String group = matcher.group();
            if (group.length() > 1) compressed += group.length() + "";
            compressed += group.charAt(0);
        }
        return compressed;
    }
    
    public static String decompress_string(String inp) {
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < inp.length(); i++) {
            char ch = inp.charAt(i);
            if (ch == '1') {
                s.append('1');
            } else {
                int count = ch - '0';
                String repeat = "" + inp.charAt(++i);
                s.append(String.join("", Collections.nCopies(count, repeat)));
            }
        }
        return s.toString();
    }
    
    public void test(String[] args) throws Exception {
        String test = "111111";
        String compressed = compress_string(test);
        String decompressed = decompress_string(compressed);
        System.out.println("test = '" + test + "' compressed = '" + compressed + "' decompressed = '" + decompressed + "'");
    }