먼저 확인할 문자열을 설정합니다.
string s = "timetime";
이제 문자열의 두 절반에 대해 두 개의 카운터를 설정합니다.
int []one = new int[MAX_CHAR]; int []two = new int[MAX_CHAR];
문자열의 절반을 모두 확인합니다.
for (int i = 0, j = l - 1; i < j; i++, j--) {
one[str[i] - 'a']++;
two[str[j] - 'a']++;
} 다음은 C#에서 문자열의 양쪽 절반에 동일한 문자 집합이 있는지 여부를 확인하는 전체 코드입니다.
예시
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!