| 3 | //Problem : Compress the given string |
| 4 | public class StringCompression { |
| 5 | public static String compressString(String str) { |
| 6 | String newStr = ""; |
| 7 | |
| 8 | for(int i=0; i<str.length(); i++) { |
| 9 | Integer count = 1; |
| 10 | |
| 11 | while(i < str.length()-1 && str.charAt(i) == str.charAt(i+1)) { |
| 12 | count++; |
| 13 | i++; |
| 14 | } |
| 15 | |
| 16 | newStr += str.charAt(i); |
| 17 | newStr = count > 1 ? newStr + count.toString() : newStr; |
| 18 | } |
| 19 | |
| 20 | return newStr; |
| 21 | } |
| 22 | public static void main(String args[]) { |
| 23 | String str = "aaabbcccdd"; |
| 24 | System.out.println(compressString(str)); |