1. 程式人生 > >【ACM】HDU 1020 Encoding (for java)

【ACM】HDU 1020 Encoding (for java)

  

解題思路:

            找出子串中相同的字元,用一個計數器記錄該字元出現的次數即可。若出現次數為1忽略1即可。

 

import java.util.Scanner;

public class Main {
	
	public static void main(String[] args) {
		
		Scanner scanner = new Scanner(System.in);
		
		int K = scanner.nextInt();
		
		for (int i = 1; i <= K; i++) {
			
			String s = scanner.next();
			
			// 記錄字串第一個字元
			char temp = s.charAt(0);
			
			// 計數
			int count = 1; 
			
			for (int j = 1; j < s.length(); j++) {
				
				if (s.charAt(j) != temp) {
							
					if ( count == 1) {
						System.out.print(s.charAt(j - 1));
					}
					else {
						System.out.print(count);
						System.out.print(s.charAt(j - 1));			
						count = 1;
					}			
					temp = s.charAt(j);	
				}
				else {
					count++;
				}
				
				if (j == s.length()-1) {
					if (count == 1) {
						System.out.print(s.charAt(j));
					}
					else {
						System.out.print(count);
						System.out.print(s.charAt(j - 1));
					}		
				}
				
			}
		System.out.println();

		}

		
		
	}
}