C# 程式檢查給定字串是否為異序構詞


字串的異序構詞是指該字串不包含重複的字母。例如:

Mobile
Cry
Laptop

迴圈遍歷字串的每個單詞,直到字串長度結束:

for (int i = 0; i < len; i++) {
   if (val[str[i] - 'a'] == 0)
   val[str[i] - 'a'] = 1;
   else
   return false;
}

其中,len 是字串的長度。

以下是完整程式碼:

示例

 動態演示

using System;

public class GFG {
   static bool checkHeterogram(string str, int len) {
      int []val = new int[26];

      for (int i = 0; i < len; i++) {
         if (val[str[i] - 'a'] == 0)
         val[str[i] - 'a'] = 1;
         else
         return false;
      }
      return true;
   }
   public static void Main () {
      string str = "mobile";

      // length of the entered string
      int len = str.Length;
      if(checkHeterogram(str, len))
      Console.WriteLine("String is Heterogram!");
      else
      Console.WriteLine("String is not a Heterogram!");
   }
}

輸出

String is Heterogram!

更新於:2020-06-22

325 檢視

開啟你的職業生涯

獲得課程認證

立即開始
廣告
© . All rights reserved.