Java compressing Strings

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

     // O(N) loop through entire character array
     // match current char with next one, if they matches count++
     // if don't then just append current char and counter value and then reset counter.
    // special case is the last characters, for that just check if count value is > 0, if it's then append the counter value and the last char
    
     private String compress(String str) {
            char[] c = str.toCharArray();
            String newStr = "";
            int count = 1;
            for (int i = 0; i < c.length - 1; i++) {
                int j = i + 1;
                if (c[i] == c[j]) {
                    count++;
                } else {
                    newStr = newStr + c[i] + count;
                    count = 1;
                }
            }
    
            // this is for the last strings...
            if (count > 0) {
                newStr = newStr + c[c.length - 1] + count;
            }
    
            return newStr;
        }
    

提交回复
热议问题