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

หาตัวอักษรที่ซ้ำครั้งแรกใน String ด้วย Java

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

import java.util.*;

public class Demo {
    static char repeat_first(char my_str[]) {
        HashSet my_hash = new HashSet<>();
        for (int i = 0; i <= my_str.length - 1; i++) {
            char c = my_str[i];
            if (my_hash.contains(c))
                return c;
            else
                my_hash.add(c);
        }
        return '\0';
    }

    public static void main(String[] args) {
        String my_str = "thisisasampleonlysample";
        char[] my_arr = my_str.toCharArray();
        System.out.println("The first repeating character in the string is :");
        System.out.println(repeat_first(my_arr));
    }
}

ผลลัพธ์

The first repeating character in the string is : i

คลาส Demo มีฟังก์ชัน repeat_first รับพารามิเตอร์เป็นอาร์เรย์ตัวอักษร สร้าง HashSet เพื่อเก็บตัวอักษรที่เคยเจอ วนลูปตรวจสอบแต่ละตัวอักษร หากเจอใน HashSet แล้ว ให้คืนค่าตัวอักษรนั้นทันที (เป็นตัวซ้ำครั้งแรก) มิฉะนั้นเพิ่มลง HashSet ใน main แปลง String เป็น char array และเรียกฟังก์ชัน