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

ตรวจสอบว่าทั้งสองครึ่งของสตริงมีชุดตัวอักษรเหมือนกันใน C#

ขั้นแรก ตั้งค่าสตริงที่ต้องการตรวจสอบ:

string s = "timetime";

ตั้งค่า counter 2 ตัวสำหรับ 2 ครึ่งของสตริง:

int[] one = new int[MAX_CHAR]; int[] two = new int[MAX_CHAR];

ตรวจสอบทั้ง 2 ครึ่ง:

for (int i = 0, j = l - 1; i < j; i++, j--) { 
    one[str[i] - 'a']++; 
    two[str[j] - 'a']++; 
}

ตัวอย่าง

using System; 
class Demo { 
    static int MAX_CHAR = 26; 
    static bool findSameCharacters(string str) { 
        int[] one = new int[MAX_CHAR]; 
        int[] two = new int[MAX_CHAR]; 
        int l = str.Length; 
        if (l == 1) return true; 
        for (int i = 0, j = l - 1; i < j; i++, j--) { 
            one[str[i] - 'a']++; 
            two[str[j] - 'a']++; 
        } 
        for (int i = 0; i < MAX_CHAR; i++) 
            if (one[i] != two[i]) return false; 
        return true; 
    } 
    public static void Main() { 
        string str = "timetime"; 
        if (findSameCharacters(str)) Console.Write("Yes: Two halves are same!"); 
        else Console.Write("No! Two halves are not same!"); 
    } 
}

ผลลัพธ์

Yes: Two halves are same!