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:25

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;
   }
查看更多
Anthone
3楼-- · 2019-01-06 20:28

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();
    }
查看更多
Lonely孤独者°
4楼-- · 2019-01-06 20:28

The easiest approach:- Time Complexity - O(n)

public static void main(String[] args) {
    String str = "AAABBBBCC";       //input String
    int length = str.length();      //length of a String

    //Created an object of a StringBuilder class        
    StringBuilder sb = new StringBuilder(); 

    int count=1;   //counter for counting number of occurances

    for(int i=0; i<length; i++){
        //if i reaches at the end then append all and break the loop
        if(i==length-1){         
            sb.append(str.charAt(i)+""+count);
            break;
        }

        //if two successive chars are equal then increase the counter
        if(str.charAt(i)==str.charAt(i+1)){   
            count++;
        }
        else{
        //else append character with its count                            
            sb.append(str.charAt(i)+""+count);
            count=1;     //reseting the counter to 1
        }
   }

    //String representation of a StringBuilder object
    System.out.println(sb.toString());   

}
查看更多
等我变得足够好
5楼-- · 2019-01-06 20:30

consider the below Solution in which the String s1 identifies the unique characters that are available in a given String s (for loop 1), in the second for loop build a string s2 that contains unique character and no of times it is repeated by comparing string s1 with s.

public static void main(String[] args) 
{
    // TODO Auto-generated method stub

    String s = "aaaabbccccffffdeee";//given string
    String s1 = ""; // string to identify how many unique letters are available in a string
    String s2=""; //decompressed string will be appended to this string
    int count=0;
    for(int i=0;i<s.length();i++) {
        if(s1.indexOf(s.charAt(i))<0) {
            s1 = s1+s.charAt(i);
        }
    }
    for(int i=0;i<s1.length();i++) {
        for(int j=0;j<s.length();j++) {
            if(s1.charAt(i)==s.charAt(j)) {
                count++;
            }
        }
        s2=s2+s1.charAt(i)+count;
        count=0;
    }

    System.out.println(s2);
}
查看更多
Bombasti
6楼-- · 2019-01-06 20:30

The code below will ask the user for user to input a specific character to count the occurrence .

import java.util.Scanner;

class CountingOccurences {

public static void main(String[] args) {

    Scanner inp = new Scanner(System.in);

    String str;
    char ch;
    int count=0;

    System.out.println("Enter the string:");
    str=inp.nextLine();
    System.out.println("Enter th Char to see the occurence\n");
    ch=inp.next().charAt(0);

    for(int i=0;i<str.length();i++)
    {
                if(str.charAt(i)==ch)
        {
            count++;
                }
    }

        System.out.println("The Character is Occuring");
        System.out.println(count+"Times");


}

}
查看更多
戒情不戒烟
7楼-- · 2019-01-06 20:31
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;
    }

}
查看更多
登录 后发表回答