2017-05-03 39 views
-2

主要方法 :使用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; 
     } 
    } 
+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); 
}