การบีบอัดข้อความด้วยการนับตัวอักษรซ้ำ
โจทย์
Implement a method to perform basic string compression using the counts of repeated characters. If the compressed string is not smaller than the original string, return the original string.
Input:
- A random string
Output:
- The compressed string or the original string is printed based on the length comparison
| Input | Output |
|---|---|
| aabcccccaaa | a2b1c5a3 |
โค้ด
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine();
String compressedText = "";
int i = 0;
while (i < text.length()) {
char c = text.charAt(i);
int count = 0;
while (i < text.length() && text.charAt(i) == c) {
count++;
i++;
}
compressedText += "" + c + count;
}
System.out.println(compressedText.length() > text.length() ? text : compressedText);
}
}คำอธิบาย
1. การประกาศคลาสและรับข้อความ
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine(); // รับข้อความ2. การเตรียมการบีบอัดข้อความ
String compressedText = ""; // สร้างสตริงว่างสำหรับเก็บผลลัพธ์3. การบีบอัดข้อความ
int i = 0;
while (i < text.length()) {
char c = text.charAt(i); // เก็บตัวอักษรปัจจุบัน
int count = 0; // นับจำนวนตัวอักษรซ้ำ
while (i < text.length() && text.charAt(i) == c) {
count++; // เพิ่มตัวนับเมื่อพบตัวอักษรซ้ำ
i++; // เลื่อนไปตัวถัดไป
}
compressedText += "" + c + count; // เพิ่มตัวอักษรและจำนวนที่ซ้ำ
}- ใช้ loop ซ้อนในการนับตัวอักษรซ้ำ:
- loop นอก: วนผ่านแต่ละตัวอักษรในข้อความ
- loop ใน: นับจำนวนตัวอักษรที่ซ้ำกัน
4. การตรวจสอบและแสดงผล
System.out.println(compressedText.length() > text.length() ? text : compressedText);- ใช้ Ternary operator เปรียบเทียบความยาว:
- ถ้าข้อความที่บีบอัดยาวกว่า: แสดงข้อความต้นฉบับ
- ถ้าข้อความที่บีบอัดสั้นกว่า: แสดงข้อความที่บีบอัด
แผนภาพการทำงาน
ตัวอย่างการทำงาน
ตัวอย่างที่ 1
Input: aabcccccaaa
การทำงาน:
1. พบ 'a' ซ้ำ 2 ครั้ง → a2
2. พบ 'b' ซ้ำ 1 ครั้ง → b1
3. พบ 'c' ซ้ำ 5 ครั้ง → c5
4. พบ 'a' ซ้ำ 3 ครั้ง → a3
ผลลัพธ์: a2b1c5a3
(ความยาว 8 < ความยาวต้นฉบับ 11)ตัวอย่างที่ 2
Input: abc
การทำงาน:
1. พบ 'a' ซ้ำ 1 ครั้ง → a1
2. พบ 'b' ซ้ำ 1 ครั้ง → b1
3. พบ 'c' ซ้ำ 1 ครั้ง → c1
ผลลัพธ์: abc
(เนื่องจาก a1b1c1 ยาว 6 > ความยาวต้นฉบับ 3)ปรับปรุงล่าสุด