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

Cách tìm chuỗi lặp lại thứ 2 trong mảng Android

Giới thiệu

Ví dụ này minh họa cách tìm chuỗi xuất hiện nhiều thứ hai (second most frequent) trong một mảng chuỗi trong Android.

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project và điền đầy đủ thông tin cần thiết.

Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="30sp"
        android:gravity="center"
        android:padding="16dp" />

</LinearLayout>

Bước 3: MainActivity.java

package com.example.myapplication;

import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class MainActivity extends AppCompatActivity {

    private final String[] strArray = {"aaa", "aaa", "bbb", "ccc", "bbb"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Bước 1: Đếm tần suất từng chuỗi
        Map frequencyMap = new HashMap<>();
        for (String s : strArray) {
            frequencyMap.merge(s, 1, Integer::sum);
        }

        // Bước 2: Sắp xếp các entry theo tần suất giảm dần
        List> sortedEntries = new ArrayList<>(frequencyMap.entrySet());
        sortedEntries.sort((e1, e2) -> e2.getValue().compareTo(e1.getValue()));

        // Bước 3: Lấy phần tử thứ 2 (index 1) nếu có
        String result;
        if (sortedEntries.size() >= 2) {
            result = sortedEntries.get(1).getKey() + " (xuất hiện " + sortedEntries.get(1).getValue() + " lần)";
        } else if (sortedEntries.size() == 1) {
            result = "Chỉ có 1 chuỗi duy nhất: " + sortedEntries.get(0).getKey();
        } else {
            result = "Mảng rỗng";
        }

        TextView textView = findViewById(R.id.text);
        textView.setText("Mảng: [aaa, aaa, bbb, ccc, bbb]\n\n" +
            "Tần suất: " + frequencyMap + "\n\n" +
            "Chuỗi lặp lại thứ 2: " + result);
    }
}

Chạy ứng dụng

Kết nối thiết bị Android thật với máy tính. Trong Android Studio, nhấn Run và chọn thiết bị để chạy.

Kết quả

Mảng: [aaa, aaa, bbb, ccc, bbb]

Tần suất: {aaa=2, bbb=2, ccc=1}

Chuỗi lặp lại thứ 2: bbb (xuất hiện 2 lần) hoặc aaa (xuất hiện 2 lần) - tùy thứ tự sắp xếp khi bằng nhau

Giải thích logic

  1. Đếm tần suất: Dùng HashMap<String, Integer>, key là chuỗi, value là số lần xuất hiện
  2. Sắp xếp: Chuyển entrySet sang List, sort theo value giảm dần
  3. Lấy index 1: Phần tử thứ 2 trong danh sách đã sắp xếp

Xử lý trường hợp hòa tần suất (tie-breaking)

// Nếu muốn ưu tiên chuỗi xuất hiện sớm hơn khi tần suất bằng nhau
sortedEntries.sort((e1, e2) -> {
    int freqCompare = e2.getValue().compareTo(e1.getValue());
    if (freqCompare != 0) return freqCompare;
    // Tần suất bằng nhau -> so sánh index xuất hiện đầu tiên
    return Integer.compare(indexOfFirst(strArray, e1.getKey()), 
                          indexOfFirst(strArray, e2.getKey()));
});

Lưu ý: Code gốc có logic lỗi (dùng HashSet làm mất thông tin tần suất, lấy list.get(size-2) không đúng). Đã viết lại đúng thuật toán: đếm → sort theo tần suất → lấy index 1. Yêu cầu API 24+ cho Stream, code thay thế dùng for-each tương thích mọi API.