ตัวอย่างโค้ด
import java.io.*;
import java.util.*;
public class Demo {
static void common_chars(String str_1, String str_2) {
int[] array_1 = new int[26];
int[] array_2 = new int[26];
int str_len_1 = str_1.length();
int str_len_2 = str_2.length();
for (int i = 0; i < str_len_1; i++)
array_1[str_1.charAt(i) - 'a'] += 1;
for (int i = 0; i < str_len_2; i++)
array_2[str_2.charAt(i) - 'a'] += 1;
for (int i = 0; i < 26; i++) {
if (array_1[i] != 0 && array_2[i] != 0) {
for (int j = 0; j < Math.min(array_1[i], array_2[i]); j++)
System.out.print((char)(i + 'a'));
}
}
}
public static void main(String[] args) throws IOException {
String my_str_1 = "itsasample";
String my_str_2 = "thisisasample";
System.out.println("The common characters between the two strings in alphabetical order is : ");
common_chars(my_str_1, my_str_2);
}
}
ผลลัพธ์
The common characters between the two strings in alphabetical order is : aaeilmpsst
คลาส Demo มีฟังก์ชัน common_chars ประกาศอาร์เรย์จำนวนเต็ม 2 ตัว ขนาด 26 (แทนตัวอักษรภาษาอังกฤษ 26 ตัว) นับจำนวนครั้งที่แต่ละตัวอักษรปรากฏในแต่ละสตริงโดยใช้ดัชนีคำนวณจาก char - 'a' จากนั้นวนลูป 0-25 หากทั้งสองอาร์เรย์มีค่ามากกว่า 0 แสดงว่าตัวอักษรตัวนั้นมีในทั้งสองสตริง จะพิมพ์ตัวอักษรนั้นจำนวนครั้งเท่ากับค่าต่ำกว่าของทั้งสองอาร์เรย์ (จำนวนที่ซ้ำกันน้อยที่สุด) ใน main กำหนดสตริง 2 ตัวและเรียกฟังก์ชัน