Java compressing Strings

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

    • use StringBuilder (you did that)
    • define two variables - previousChar and counter
    • loop from 0 to str.length() - 1
    • each time get str.charat(i) and compare it to what's stored in the previousChar variable
    • if the previous char is the same, increment a counter
    • if the previous char is not the same, and counter is 1, increment counter
    • if the previous char is not the same, and counter is >1, append counter + currentChar, reset counter
    • after the comparison, assign the current char previousChar
    • cover corner cases like "first char"

    Something like that.

提交回复
热议问题