ตรวจสอบว่าสตริงมีตัวอักษรซ้ำหรือไม่ (All Unique Characters) ใน C#
วิธีง่ายที่สุดคือใช้ Nested Loop เปรียบเทียบตัวอักษรทุกคู่ (Time Complexity O(n²)) หรือใช้ HashSet เพื่อประสิทธิภาพ O(n)
วิธีที่ 1: Nested Loop (เข้าใจง่าย)
public static bool HasUniqueChars(string input)
{
for (int i = 0; i < input.Length; i++)
{
for (int j = i + 1; j < input.Length; j++)
{
if (input[i] == input[j])
return false; // พบตัวซ้ำ
}
}
return true; // ไม่มีตัวซ้ำ
}
วิธีที่ 2: ใช้ HashSet (แนะนำ - เร็วกว่า)
public static bool HasUniqueCharsHashSet(string input)
{
var seen = new HashSet();
foreach (char c in input)
{
if (!seen.Add(c)) // Add คืนค่า false หากมีอยู่แล้ว
return false;
}
return true;
}
วิธีที่ 3: ใช้ Bit Vector (สำหรับ ASCII เท่านั้น - เร็วที่สุด)
public static bool HasUniqueCharsBitVector(string input)
{
if (input.Length > 128) return false; // ASCII มีแค่ 128 ตัว
int checker = 0;
foreach (char c in input)
{
int val = c - 'a'; // สมมติ a-z เท่านั้น
if ((checker & (1 << val)) > 0)
return false;
checker |= (1 << val);
}
return true;
}
ตัวอย่างการใช้งาน
using System;
class Program
{
static void Main()
{
string[] tests = { "abcde", "hello", "world", "unique" };
foreach (var s in tests)
{
Console.WriteLine($"'{s}': Unique = {HasUniqueCharsHashSet(s)}");
}
}
static bool HasUniqueCharsHashSet(string input)
{
var seen = new HashSet();
foreach (char c in input)
if (!seen.Add(c)) return false;
return true;
}
}
ผลลัพธ์
'abcde': Unique = True
'hello': Unique = False
'world': Unique = True
'unique': Unique = False