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

更新日期: 2020 年 6 月 23 日

166 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

入門
廣告