Java compressing Strings

2019-01-06 19:58发布

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 and I couldn't manage to do it on the interview that I had today ( I was applying for a Junior position ), now, trying at home I made something that works statically, I mean, not using a loop which is kind of useless but I don't know if I'm not getting enough hours of sleep or something but I can't figure it out how my for loop should look like. This is the code:

public static String Comprimir(String texto){

    StringBuilder objString = new StringBuilder();

    int count;
    char match;

        count = texto.substring(texto.indexOf(texto.charAt(1)), texto.lastIndexOf(texto.charAt(1))).length()+1;
        match = texto.charAt(1);
        objString.append(count);
        objString.append(match);

    return objString.toString();
}

Thanks for your help, I'm trying to improve my logic skills.

17条回答
不美不萌又怎样
2楼-- · 2019-01-06 20:32
private String Comprimir(String input){
        String output="";
        Map<Character,Integer> map=new HashMap<Character,Integer>();
        for(int i=0;i<input.length();i++){
            Character character=input.charAt(i);
            if(map.containsKey(character)){
                map.put(character, map.get(character)+1);
            }else
                map.put(character, 1);
        }
        for (Entry<Character, Integer> entry : map.entrySet()) {
            output+=entry.getValue()+""+entry.getKey().charValue();
        }
        return output;
    }

One other simple way using Multiset of guava-

import java.util.Arrays;

import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multiset.Entry;

public class WordSpit {
    public static void main(String[] args) {
        String output="";
        Multiset<String> wordsMultiset = HashMultiset.create();
        String[] words="AAABBBBCC".split("");
        wordsMultiset.addAll(Arrays.asList(words));
        for (Entry<String> string : wordsMultiset.entrySet()) {
            if(!string.getElement().isEmpty())
                output+=string.getCount()+""+string.getElement();
        }
        System.out.println(output);
    }
}
查看更多
甜甜的少女心
3楼-- · 2019-01-06 20:33

Please try this one. This may help to print the count of characters which we pass on string format through console.

import java.util.*;

public class CountCharacterArray {
   private static Scanner inp;

public static void main(String args[]) {
   inp = new Scanner(System.in);
  String  str=inp.nextLine();
   List<Character> arrlist = new ArrayList<Character>();
   for(int i=0; i<str.length();i++){
       arrlist.add(str.charAt(i));
   }
   for(int i=0; i<str.length();i++){
       int freq = Collections.frequency(arrlist, str.charAt(i));
       System.out.println("Frequency of "+ str.charAt(i)+ "  is:   "+freq); 
   }
     }    
}
查看更多
我想做一个坏孩纸
4楼-- · 2019-01-06 20:34
public class StringCompression {
    public static void main(String[] args){
        String s = "aabcccccaaazdaaa";

        char check = s.charAt(0);
        int count = 0;

        for(int i=0; i<s.length(); i++){
            if(s.charAt(i) == check) {
                count++;
                if(i==s.length()-1){
                System.out.print(s.charAt(i));
                System.out.print(count);
             }
            } else {
                System.out.print(s.charAt(i-1));
                System.out.print(count);
                check = s.charAt(i);
                count = 1;
                if(i==s.length()-1){
                    System.out.print(s.charAt(i));
                    System.out.print(count);
                 }
            }
        }
    }
查看更多
虎瘦雄心在
5楼-- · 2019-01-06 20:38

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());
查看更多
Fickle 薄情
6楼-- · 2019-01-06 20:41

You can do that using the following steps:

  • Create a HashMap
  • For every character, Get the value from the hashmap -If the value is null, enter 1 -else, replace the value with (value+1)
  • Iterate over the HashMap and keep concatenating (Value+Key)
查看更多
等我变得足够好
7楼-- · 2019-01-06 20:41
public static char[] compressionTester( char[] s){

    if(s == null){
        throw new IllegalArgumentException();
    }

    HashMap<Character, Integer> 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;               
    }                       
}
查看更多
登录 后发表回答