Java compressing Strings

前端 未结 20 1051
误落风尘
误落风尘 2020-11-29 09:24

I need to create a method that receives a String and also returns a String.

Ex input: AAABBBBCC

Ex output: 3A4B2C

Well, this is quite embarrassing a

20条回答
  •  清歌不尽
    2020-11-29 10:15

    Java's not my main language, hardly ever use it, but I wanted to give it a shot :] Not even sure if your assignment requires a loop, but here's a regexp approach:

     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;
       }
    

提交回复
热议问题