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

โปรแกรม C# ตรวจสอบว่าสองคำเป็น Anagram กันหรือไม่


ภาพรวม

Anagram (อะนาแกรม) คือ คำที่ประกอบด้วยตัวอักษรชุดเดียวกัน แต่เรียงลำดับต่างกัน (เช่น "heater" และ "reheat")

อัลกอริทึม

  1. แปลงทั้งสองสตริงเป็น lowercase (case-insensitive)
  2. แปลงเป็น char array
  3. จัดเรียง (sort) ทั้งสองอาร์เรย์
  4. เปรียบเทียบว่าเท่ากันหรือไม่

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

using System;

public class Demo
{
    public static void Main()
    {
        string str1 = "heater";
        string str2 = "reheat";
        char[] ch1 = str1.ToLower().ToCharArray();
        char[] ch2 = str2.ToLower().ToCharArray();
        Array.Sort(ch1);
        Array.Sort(ch2);
        string val1 = new string(ch1);
        string val2 = new string(ch2);
        if (val1 == val2)
            Console.WriteLine("Both the strings are Anagrams");
        else
            Console.WriteLine("Both the strings are not Anagrams");
    }
}

ผลลัพธ์

Both the strings are Anagrams

วิธีอื่นๆ (มีประสิทธิภาพมากกว่า)

  • นับความถี่ตัวอักษร: int[26] counts = new int[26]; foreach(c in s1) counts[c-'a']++; foreach(c in s2) counts[c-'a']--; // all zero = anagram - O(n) time, O(1) space
  • LINQ: str1.OrderBy(c => c).SequenceEqual(str2.OrderBy(c => c))