检查字符串的两个半部分在 C# 中是否具有相同的字符集
首先,设置要检查的字符串。
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!
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 程序设计
C++
C#
MongoDB
MySQL
Javascript
PHP