Java compressing Strings

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

    public static char[] compressionTester( char[] s){
    
        if(s == null){
            throw new IllegalArgumentException();
        }
    
        HashMap map = new HashMap<>();
        for (int i = 0 ; i < s.length ; i++) {
    
            if(!map.containsKey(s[i])){
                map.put(s[i], 1);
            }
            else{
                int value = map.get(s[i]);
                value++;
                map.put(s[i],value);
            }           
        }               
        String newer="";
    
        for( Character n : map.keySet()){
    
            newer = newer + n + map.get(n); 
        }
        char[] n = newer.toCharArray();
    
        if(s.length > n.length){
            return n;
        }
        else{
    
            return s;               
        }                       
    }
    

提交回复
热议问题