2017-05-03 7 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); 
} 
関連する問題