Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Tìm từ lặp lại thứ hai nhiều nhất trong chuỗi trong Java


Để tìm từ lặp lại thứ hai nhiều nhất trong chuỗi trong Java, mã như sau:

Ví dụ

import java.util.*; public class Demo{    static String second_repeated(Vector<String> my_seq){       HashMap <String, Integer> my_map = new HashMap<String,Integer>(my_seq.size()){          @Override          public Integer get(Object key){             return containsKey(key) ? super.get(key) : 0;          }       };       for (int i = 0; i < my_seq.size(); i++)       my_map.put(my_seq.get(i), my_map.get(my_seq.get(i))+1);       int first_val = Integer.MIN_VALUE;       int sec_val = Integer.MIN_VALUE;       Iterator<Map.Entry<String, Integer>> my_iter = my_map.entrySet().iterator();       while (my_iter.hasNext()){          Map.Entry<String, Integer> ent = my_iter.next();          int v = ent.getValue();          if( v > first_val){             sec_val = first_val;             first_val = v;          }          else if (v > sec_val && v != first_val)          sec_val = v;       }       my_iter = my_map.entrySet().iterator();       while (my_iter.hasNext()){          Map.Entry<String, Integer> ent = my_iter.next();          int v = ent.getValue();          if (v == sec_val)          return ent.getKey();       }       return null;    }    public static void main(String[] args){       String arr[] = {"This", "sample", "only", "anything", "sample", "from", "sample","only"};       List<String> my_seq = Arrays.asList(arr);       System.out.println("The second most repeated word in the sequence is : ");       System.out.println(second_repeated(new Vector<>(my_seq)));    } }

Kết quả

The second most repeated word in the sequence is : Only

Lớp Demo chứa hàm second_repeated tạo hash map và ghi đè get trả về key của giá trị cụ thể. Iterator tạo, các phần tử tiếp theo lặp qua hasNext.

Iterator kiểm tra số lần từ lặp lại, từ lặp nhiều nhất tìm được lưu. Làm lại hành động cho từ lặp lại thứ hai. Lớp main chứa mảng chuỗi và list. Mảng chuỗi chuyển thành list. Hàm second_repeated gọi trên list mới. Đầu ra hiển thị.