Java compressing Strings

前端 未结 20 1044
误落风尘
误落风尘 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;
        }
    
    }
    

提交回复
热议问题