Java compressing Strings

前端 未结 20 1036
误落风尘
误落风尘 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:14

    In the count=... line, lastIndexOf will not care about consecutive values, and will just give the last occurence.

    For instance, in the string "ABBA", the substring would be the whole string.

    Also, taking the length of the substring is equivalent to subtracting the two indexes.

    I really think that you need a loop. Here is an example :

    public static String compress(String text) {
        String result = "";
    
        int index = 0;
    
        while (index < text.length()) {
            char c = text.charAt(index);
            int count = count(text, index);
            if (count == 1)
                result += "" + c;
            else
                result += "" + count + c;
            index += count;
        }
    
        return result;
    }
    
    public static int count(String text, int index) {
        char c = text.charAt(index);
        int i = 1;
        while (index + i < text.length() && text.charAt(index + i) == c)
            i++;
        return i;
    }
    
    public static void main(String[] args) {
        String test = "AAABBCCC";
        System.out.println(compress(test));
    }
    

提交回复
热议问题