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

Cách tìm ký tự không lặp lại đầu tiên trong chuỗi Android

Giới thiệu

Ví dụ này minh họa cách tìm ký tự không lặp lại đầu tiên (first non-repeating character) trong một chuỗi cho trước 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.LinkedHashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private final String inputString = "tutorialspoint";

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

        // LinkedHashMap: Giữ thứ tự chèn (insertion order) - quan trọng để tìm "đầu tiên"
        Map charCount = new LinkedHashMap<>();

        // Bước 1: Đếm tần suất từng ký tự, giữ thứ tự xuất hiện
        for (char c : inputString.toCharArray()) {
            charCount.merge(c, 1, Integer::sum);
        }
        // charCount = {t=2, u=2, o=2, r=1, i=2, a=1, l=1, s=1, p=1, n=1}

        // Bước 2: Tìm ký tự đầu tiên có count = 1
        Character firstNonRepeating = null;
        for (Map.Entry entry : charCount.entrySet()) {
            if (entry.getValue() == 1) {
                firstNonRepeating = entry.getKey();
                break; // Tìm thấy ký tự không lặp đầu tiên -> dừng
            }
        }

        TextView textView = findViewById(R.id.text);
        if (firstNonRepeating != null) {
            textView.setText("Chuỗi: " + inputString + 
                "\n\nKý tự không lặp lại đầu tiên: '" + firstNonRepeating + "'" +
                "\n\nChi tiết đếm: " + charCount);
        } else {
            textView.setText("Chuỗi: " + inputString + "\n\nKhông có ký tự nào không lặp lại");
        }
    }
}

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ả

Chuỗi: "tutorialspoint"

Ký tự không lặp lại đầu tiên: 'r'

Giải thích: t(2), u(2), t(2), o(2), r(1) ← đầu tiên có count=1

Giải thích thuật toán

  1. LinkedHashMap: Quan trọng! Giữ thứ tự chèn (insertion order) để duyệt theo thứ tự xuất hiện trong chuỗi
  2. Đếm tần suất: Duyệt chuỗi một lần O(n)
  3. Tìm first non-repeating: Duyệt map một lần O(k) với k = số ký tự khác nhau
  4. Tổng độ phức tạp: O(n) thời gian, O(k) không gian

Cách thay thế (API 24+ Stream)


Character result = inputString.chars()
    .mapToObj(c -> (char) c)
    .collect(Collectors.groupingBy(
        c -> c, 
        LinkedHashMap::new, 
        Collectors.counting()))
    .entrySet().stream()
    .filter(e -> e.getValue() == 1)
    .map(Map.Entry::getKey)
    .findFirst()
    .orElse(null);

Lưu ý: Code gốc có lỗi logic (hashMap.put(strArray.charAt(i), chars[i] + 1) cộng giá trị char thay vì đếm). Đã sửa dùng merge() hoặc put(key, count+1). LinkedHashMap là chìa khóa để giữ thứ tự. Loại bỏ import không cần thiết và @RequiresApi.