创建基本压缩算法

时间:2017-05-03 18:33:12

标签: java algorithm compression

主要方法 :使用SparseCompression()获取整数数组并将其压缩为字符串。

public class Compress
{
   public static void main(String[] args)
   {
      int[] test = {0, 0, 0, 0, 0, 0, 0, 999};
      String result = SparseCompression(test);

      // expected result: "#7,999," 
      System.out.println(result);
      //need to compress something like(2,0,0,0,54,0,0,2)
      // expected result: "2,#3,54,#2,2"
   }

压缩算法: 到目前为止,数组必须以连续的零开始,然后在第一个非零结束。需要能够以非零开始并继续直到数组结束。像(4,0,0,0,0,45,65,0,0,0,5)这样的东西。

public static String SparseCompression(int[] array)
   {  
      int count = 0;
      int nonZero = 0;
      int after = 0;
      for(int i = 0; i< array.length; i++)
      {
         if(array[i] == 0)
         {
            count++;
         }
         else if(array[i] != 0)
         {
           nonZero = array[i];
         }

      }
      Integer.toString(count);
      String result = "#" + count + ", " + nonZero;
      return result;
      }
   }

1 个答案:

答案 0 :(得分:0)

public static String SparseCompression(int[] array) {
    if (null == array || array.length == 0) {
        return "";
    }
    StringBuilder sb = new StringBuilder();
    int count = 0;
    for (int a : array) {
        if (a == 0) {
            count++;
            continue;
        }
        if (count != 0) {
            sb.append("#" + count + ",");
            count = 0;
        }
        sb.append(a + ",");
    }
    if (count != 0) {
        sb.append("#" + count + ",");
    }
    return sb.toString().substring(0, sb.length() - 1);
}
相关问题