Java compressing Strings

前端 未结 20 1017
误落风尘
误落风尘 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:55
    package com.tell.datetime;
    
    import java.util.Stack;
    public class StringCompression {
        public static void main(String[] args) {
            String input = "abbcccffffdd";
            System.out.println(compressString(input));
        }
    
        public static String compressString(String input) {
    
            if (input == null || input.length() == 0)
                return input;
            String finalCompressedString = "";
            String lastElement="";
            char[] charArray = input.toCharArray();
            Stack stack = new Stack();
            int elementCount = 0;
            for (int i = 0; i < charArray.length; i++) {
                char currentElement = charArray[i];
                if (i == 0) {
                    stack.push((currentElement+""));
                    continue;
                } else {
                    if ((currentElement+"").equalsIgnoreCase((String)stack.peek())) {
                        stack.push(currentElement + "");
                        if(i==charArray.length-1)
                        {
                            while (!stack.isEmpty()) {
    
                                lastElement = (String)stack.pop();
                                elementCount++;
                            }
    
                            finalCompressedString += lastElement + "" + elementCount;
                        }else
                        continue;
                    }
    
                    else {
                        while (!stack.isEmpty()) {
    
                            lastElement = (String)stack.pop();
                            elementCount++;
                        }
    
                        finalCompressedString += lastElement + "" + elementCount;
                        elementCount=0;
                        stack.push(currentElement+"");
                    }
    
                }
            }
    
            if (finalCompressedString.length() >= input.length())
                return input;
            else
                return finalCompressedString;
        }
    
    }
    
    0 讨论(0)
  • 2020-11-29 09:56
    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);
                     }
                }
            }
        }
    
    0 讨论(0)
  • 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());
    
    0 讨论(0)
  • 2020-11-29 09:59

    The following can be used if you are looking for a basic solution. Iterate through the string with one element and after finding all the element occurrences, remove that character. So that it will not interfere in the next search.

    public static void main(String[] args) {
        String string = "aaabbbbbaccc";
        int counter;
        String result="";
        int i=0;
        while (i<string.length()){
            counter=1;
            for (int j=i+1;j<string.length();j++){ 
                System.out.println("string length ="+string.length());  
                if (string.charAt(i) == string.charAt(j)){
                      counter++;
                }
          }
          result = result+string.charAt(i)+counter; 
          string = string.replaceAll(String.valueOf(string.charAt(i)), ""); 
        }
        System.out.println("result is = "+result);
    }
    

    And the output will be := result is = a4b5c3

    0 讨论(0)
  • 2020-11-29 10:01
    • use StringBuilder (you did that)
    • define two variables - previousChar and counter
    • loop from 0 to str.length() - 1
    • each time get str.charat(i) and compare it to what's stored in the previousChar variable
    • if the previous char is the same, increment a counter
    • if the previous char is not the same, and counter is 1, increment counter
    • if the previous char is not the same, and counter is >1, append counter + currentChar, reset counter
    • after the comparison, assign the current char previousChar
    • cover corner cases like "first char"

    Something like that.

    0 讨论(0)
  • 2020-11-29 10:02
    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;               
        }                       
    }
    
    0 讨论(0)
提交回复
热议问题