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

Kiểm tra 2 nửa chuỗi có cùng tập ký tự trong C#

Chuỗi cần kiểm tra: string s = "timetime";

2 counter cho 2 nửa chuỗi:

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

Kiểm tra 2 nửa:

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

Ví dụ hoàn chỉnh

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!");
    }
}

Kết quả

Yes: Two halves are same!