Java compressing Strings

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

    The answers which used Map will not work for cases like aabbbccddabc as in that case the output should be a2b3c2d2a1b1c1.

    In that case this implementation can be used :

    private String compressString(String input) {
            String output = "";
            char[] arr = input.toCharArray();
            Map myMap = new LinkedHashMap<>();
            for (int i = 0; i < arr.length; i++) {
                if (i > 0 && arr[i] != arr[i - 1]) {
                    output = output + arr[i - 1] + myMap.get(arr[i - 1]);
                    myMap.put(arr[i - 1], 0);
                }
                if (myMap.containsKey(arr[i])) {
                    myMap.put(arr[i], myMap.get(arr[i]) + 1);
                } else {
                    myMap.put(arr[i], 1);
                }
            }
    
            for (Character c : myMap.keySet()) {
                if (myMap.get(c) != 0) {
                    output = output + c + myMap.get(c);
                }
            }
    
            return output;
        }
    

提交回复
热议问题