Java compressing Strings

前端 未结 20 1019
误落风尘
误落风尘 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:12
    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);
        }
    }
    
    0 讨论(0)
  • 2020-11-29 10:13

    This is just one more way of doing it.

    public static String compressor(String raw) {
            StringBuilder builder = new StringBuilder();
            int counter = 0;
            int length = raw.length();
            int j = 0;
            while (counter < length) {
                j = 0;
                while (counter + j < length && raw.charAt(counter + j) == raw.charAt(counter)) {
                    j++;
                }
    
                if (j > 1) {
                    builder.append(j);
                }
                builder.append(raw.charAt(counter));
                counter += j;
            }
    
            return builder.toString();
        }
    
    0 讨论(0)
  • 2020-11-29 10:14

    In the count=... line, lastIndexOf will not care about consecutive values, and will just give the last occurence.

    For instance, in the string "ABBA", the substring would be the whole string.

    Also, taking the length of the substring is equivalent to subtracting the two indexes.

    I really think that you need a loop. Here is an example :

    public static String compress(String text) {
        String result = "";
    
        int index = 0;
    
        while (index < text.length()) {
            char c = text.charAt(index);
            int count = count(text, index);
            if (count == 1)
                result += "" + c;
            else
                result += "" + count + c;
            index += count;
        }
    
        return result;
    }
    
    public static int count(String text, int index) {
        char c = text.charAt(index);
        int i = 1;
        while (index + i < text.length() && text.charAt(index + i) == c)
            i++;
        return i;
    }
    
    public static void main(String[] args) {
        String test = "AAABBCCC";
        System.out.println(compress(test));
    }
    
    0 讨论(0)
  • 2020-11-29 10:14

    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); 
       }
         }    
    }
    
    0 讨论(0)
  • 2020-11-29 10:15

    Java's not my main language, hardly ever use it, but I wanted to give it a shot :] Not even sure if your assignment requires a loop, but here's a regexp approach:

     public static String compress_string(String inp) {
          String compressed = "";
          Pattern pattern = Pattern.compile("([\\w])\\1*");
          Matcher matcher = pattern.matcher(inp);
          while(matcher.find()) {
             String group = matcher.group();
             if (group.length() > 1) compressed += group.length() + "";
             compressed += group.charAt(0);
          }
          return compressed;
       }
    
    0 讨论(0)
  • 2020-11-29 10:16
     // O(N) loop through entire character array
     // match current char with next one, if they matches count++
     // if don't then just append current char and counter value and then reset counter.
    // special case is the last characters, for that just check if count value is > 0, if it's then append the counter value and the last char
    
     private String compress(String str) {
            char[] c = str.toCharArray();
            String newStr = "";
            int count = 1;
            for (int i = 0; i < c.length - 1; i++) {
                int j = i + 1;
                if (c[i] == c[j]) {
                    count++;
                } else {
                    newStr = newStr + c[i] + count;
                    count = 1;
                }
            }
    
            // this is for the last strings...
            if (count > 0) {
                newStr = newStr + c[c.length - 1] + count;
            }
    
            return newStr;
        }
    
    0 讨论(0)
提交回复
热议问题