实现基本字符串压缩

时间:2015-08-19 19:55:40

标签: java string arraylist char compression

我正在从Cracking The Coding访谈一书中的问题1.5上工作。问题是取一个字符串“aabcccccaaa”并将其转换为a2b1c5a3。

如果压缩字符串不小于原始字符串,则返回原始字符串。

我的代码如下。我使用了一个ArrayList,因为我不知道压缩字符串会有多长。

我的输出是[a,2,b,1,c,5],aabc,[]。当程序到达字符串的末尾时,它没有一个字符来比较最后一个字符。

import java.util.*;
import java.io.*;

public class stringCompression {

public static void main(String[] args) {

String a = "aabcccccaaa";
String b = "aabc";
String v = "aaaa";

check(a);
System.out.println("");
check(b);
System.out.println("");
check(v);

}


public static void check(String g){

ArrayList<Character> c = new ArrayList<Character>();
int count = 1;
int i = 0;
int h = g.length();


for(int j = i + 1; j < g.length(); j++)
 {
  if(g.charAt(i) == g.charAt(j)){
     count++;

 }

 else {
     c.add(g.charAt(i));
     c.add((char)( '0' + count));
     i = j;
     count = 1;
 }

}


if(c.size() == g.length()){
System.out.print(g);
}

else{

System.out.print(c);
}
}

}

4 个答案:

答案 0 :(得分:1)

在最后一个循环中,您没有将结果添加到数组中。当j = g.length()时,仍然需要将当前char和count添加到数组中。所以你可以在增加它之前检查j的下一个值:

for(int j = i + 1; j < g.length(); j++)


{
  if(g.charAt(i) == g.charAt(j)){
     count++;

 }

 else {
     c.add(g.charAt(i));
     c.add((char)( '0' + count));
     i = j;
     count = 1;
 }

 if((j + 1) = g.length()){

    c.add(g.charAt(i));
    c.add((char)( '0' + count));
 }

}

答案 1 :(得分:1)

我会使用StringBuilder而不是ArrayList来构建压缩的String。当您开始压缩时,应该已将第一个字符添加到结果中。一旦遇到不同的角色,就会添加角色的数量。当您到达String的末尾时,您应该将剩余的计数附加到最后一个字母的结果中。

public static void main(String[] args) throws Exception {
    String[] data = new String[] {
        "aabcccccaaa",
        "aabc",
        "aaaa"
    };

    for (String d : data) {
        System.out.println(compress(d));
    }
}

public static String compress(String str) {
    StringBuilder compressed = new StringBuilder();

        // Add first character to compressed result
        char currentChar = str.charAt(0);
        compressed.append(currentChar);

        // Always have a count of 1
        int count = 1;
        for (int i = 1; i < str.length(); i++) {
            char nextChar = str.charAt(i);
            if (currentChar == nextChar) {
                count++;
            } else {
                // Append the count of the current character
                compressed.append(count);

                // Set the current character and count
                currentChar = nextChar;
                count = 1;

                // Append the new current character
                compressed.append(currentChar);
            }
        }
        // Append the count of the last character
        compressed.append(count);

        // If the compressed string is not smaller than the original string, then return the original string
        return (compressed.length() < str.length() ? compressed.toString() : str);
}

结果:

a2b1c5a3
aabc
a4

答案 2 :(得分:0)

您有两个错误: 错字提到的一个,因为你的最后一个角色没有加入; 另一个,如果原始字符串更短,如“abc”只有三个字符:“a1b1c1”有六个字符(任务是“如果压缩字符串不小于原始字符串,则返回原始字符串。”)

您必须更改if语句,请求&gt; =而不是==

if(c.size() >= g.length()){
    System.out.print(g);
} else {
    System.out.print(c);
}

答案 3 :(得分:0)

使用StringBuilder然后迭代输入字符串。

private static string CompressString(string inputString)
{
    var count = 1;
    var compressedSb = new StringBuilder();

    for (var i = 0; i < inputString.Length; i++)
    {
        // Check if we are at the end
        if(i == inputString.Length - 1)
        {
            compressedSb.Append(inputString[i] + count.ToString());
            break;
        }

        if (inputString[i] == inputString[i + 1])
            count++;
        else
        {
            compressedSb.Append(inputString[i] + count.ToString());
            count = 1;
        }
    }

    var compressedString = compressedSb.ToString();

    return compressedString.Length > inputString.Length ? inputString : compressedString;
}
相关问题