Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java หาคำที่มีรูปแบบใกล้เคียง (Close Matches) จาก List

ตัวอย่างโค้ด

import java.io.*;
import java.util.*;

public class Demo {
    static String string_encoding(String str) {
        HashMap my_map = new HashMap<>();
        String result = "";
        int i = 0;
        char ch;
        for (int j = 0; j < str.length(); j++) {
            ch = str.charAt(j);
            if (!my_map.containsKey(ch))
                my_map.put(ch, i++);
            result += my_map.get(ch);
        }
        return result;
    }

    static void match_words(String[] my_arr, String my_pattern) {
        int len = my_pattern.length();
        String hash_val = string_encoding(my_pattern);
        for (String word : my_arr) {
            if (word.length() == len && string_encoding(word).equals(hash_val))
                System.out.print(word + " ");
        }
    }

    public static void main(String args[]) {
        String[] my_arr = {"mno", "aabb", "pqr", "xxyy", "mmnn"};
        String my_pattern = "ddcc";
        System.out.println("The patterns similar to ddcc in the array are :");
        match_words(my_arr, my_pattern);
    }
}

ผลลัพธ์

The patterns similar to ddcc in the array are : aabb xxyy mmnn

คลาส Demo มีฟังก์ชัน string_encoding สร้าง HashMap map ตัวอักษรแต่ละตัวให้กับหมายเลขลำดับที่เจอครั้งแรก (0, 1, 2...) สร้างสตริงรหัส (encoding) จากลำดับนี้ ฟังก์ชัน match_words เข้ารหัส pattern แล้วเปรียบเทียบกับแต่ละคำในอาร์เรย์ หากความยาวเท่ากันและ encoding เหมือนกัน แสดงว่ามีรูปแบบการซ้ำของตัวอักษรเหมือนกัน จะพิมพ์คำนั้นออกมา