close

問題描述 :

Run Length Encoding (RLE) 編碼方式是多媒體資料壓縮常用的方法之一 ( 例如與 Huffman Code 並用 ) , RLE 的作法是於將一連串相同的資料改以兩個部分來表示 , 前面一部分是資料本身 (symbol) ,後面部分代表該串資料的長度 ( 也就是重複次數 , run length) 。例如 : 輸入字串為 “ aaaabbcdeeeeefghhhij ”,經過 RLE 編碼後結果為 "a4b2c1d1e5f1g1h3i1j1" 。

輸入說明 :

輸入一行由小寫英文字母組成的字串 
字串長度<=50。

輸出說明 :

輸出字串編碼後的結果

範例 :

題目來源:http://e-tutor.itsa.org.tw/e-Tutor/mod/programming/view.php?id=20786

import java.util.Scanner;

public class C_ST92 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);   
        while(sc.hasNext()){   
            String str=sc.nextLine();
            int num=1;
            for(int i=1;i<str.length();i++){
                if(str.substring(i, i+1).equals(str.substring(i-1, i-1+1))){
                    num++;
                }else{
                    System.out.print(str.substring(i-1, i-1+1)+num);
                    num=1;
                }    
                if(i==str.length()-1){
                    System.out.print(str.substring(i,i+1)+num);
                }
            }
            System.out.println();
        }

    }

}
 

arrow
arrow
    文章標籤
    Java ITSA
    全站熱搜

    阿雅 發表在 痞客邦 留言(0) 人氣()