檢查字串的兩個半部分在 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