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

วิธีตรวจสอบ Anagram และนับจำนวน Anagram ใน Android

ภาพรวม

ตัวอย่างนี้สาธิตวิธีตรวจสอบ Anagram และนับจำนวนครั้งที่ Anagram ปรากฏในสตริง (Count Occurrences of Anagrams) ใน Android

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

เปิด Android Studio ไปที่ File → New Project กรอกรายละเอียดที่จำเป็นทั้งหมดเพื่อสร้างโปรเจกต์ใหม่

ขั้นตอนที่ 2: จัดทำ Layout (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:gravity="center"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">
    <EditText
        android:id="@+id/edit_query"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter text to search in" />
    <EditText
        android:id="@+id/edit_query1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter pattern (anagram to find)" />
    <Button
        android:id="@+id/buttonPanel"
        android:text="Count Anagrams"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

ขั้นตอนที่ 3: เขียนโค้ดหลัก (src/MainActivity.java)

package com.example.myapplication;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    EditText editQuery, editQuery1;

    @RequiresApi(api = Build.VERSION_CODES.P)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editQuery = findViewById(R.id.edit_query);
        editQuery1 = findViewById(R.id.edit_query1);

        findViewById(R.id.buttonPanel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = editQuery.getText().toString().trim();
                String pattern = editQuery1.getText().toString().trim();

                if (text.isEmpty() || pattern.isEmpty()) {
                    Toast.makeText(MainActivity.this, "Please enter both fields", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (areAnagrams(text, pattern)) {
                    int count = countAnagramOccurrences(text, pattern);
                    Toast.makeText(MainActivity.this, "Anagram count: " + count, Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(MainActivity.this, "Not anagrams", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    // นับจำนวน Anagram ของ pattern ใน text
    private int countAnagramOccurrences(String text, String pattern) {
        int count = 0;
        int n = pattern.length();
        
        for (int i = 0; i <= text.length() - n; i++) {
            String substring = text.substring(i, i + n);
            if (areAnagrams(pattern, substring)) {
                count++;
            }
        }
        return count;
    }

    // ตรวจสอบ Anagram (ปรับปรุงประสิทธิภาพ)
    private boolean areAnagrams(String first, String second) {
        if (first.length() != second.length()) return false;

        first = first.toLowerCase().replaceAll("\\s+", "");
        second = second.toLowerCase().replaceAll("\\s+", "");

        int[] charCount = new int[26];
        for (char c : first.toCharArray()) {
            if (c >= 'a' && c <= 'z') charCount[c - 'a']++;
        }
        for (char c : second.toCharArray()) {
            if (c >= 'a' && c <= 'z') charCount[c - 'a']--;
        }
        for (int c : charCount) {
            if (c != 0) return false;
        }
        return true;
    }
}

การทดสอบ

รันแอป ตัวอย่าง: text="forxxorfxdofr" pattern="for" → พบ Anagram 3 ครั้ง (for, orf, ofr)

อัลกอริทึม Sliding Window (ประสิทธิภาพดีกว่า)

// วิธีที่เร็วกว่าสำหรับข้อความยาว
private int countAnagramsOptimized(String text, String pattern) {
    int[] patternCount = new int[26];
    int[] windowCount = new int[26];
    
    for (char c : pattern.toCharArray()) {
        patternCount[c - 'a']++;
    }
    
    int count = 0;
    for (int i = 0; i < text.length(); i++) {
        // เพิ่มตัวอักษรใหม่เข้า window
        windowCount[text.charAt(i) - 'a']++;
        
        // ลบตัวอักษรเก่าออกจาก window (ถ้าขนาดเกิน pattern)
        if (i >= pattern.length()) {
            windowCount[text.charAt(i - pattern.length()) - 'a']--;
        }
        
        // เปรียบเทียบ
        if (java.util.Arrays.equals(patternCount, windowCount)) {
            count++;
        }
    }
    return count;
}

ความซับซ้อน

  • วิธีเดิม: O(N × M) โดย N=ความยาว text, M=ความยาว pattern
  • Sliding Window: O(N) - เร็วกว่ามากสำหรับข้อความยาว