Java compressing Strings

前端 未结 20 1052
误落风尘
误落风尘 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 09:58

    Loop through the string remembering what you last saw. Every time you see the same letter count. When you see a new letter put what you have counted onto the output and set the new letter as what you have last seen.

    String input = "AAABBBBCC";
    
    int count = 1;
    
    char last = input.charAt(0);
    
    StringBuilder output = new StringBuilder();
    
    for(int i = 1; i < input.length(); i++){
        if(input.charAt(i) == last){
        count++;
        }else{
            if(count > 1){
                output.append(""+count+last);
            }else{
                output.append(last);
            }
        count = 1;
        last = input.charAt(i);
        }
    }
    if(count > 1){
        output.append(""+count+last);
    }else{
        output.append(last);
    }
    System.out.println(output.toString());
    

提交回复
热议问题