Python 程序检查给定的字符串是否异构词


这里给定一个字符串,我们的任务是检查给定的字符串是否为异构词。

异构词检查的含义是,一个单词、短语或句子中没有一个字母出现超过一次。异构词可以与全异序词区分开来,后者使用所有字母表中的字母。

示例

字符串是 abc def ghi

This is Heterogram (no alphabet repeated)

字符串是 abc bcd dfh

This is not Heterogram. (b,c,d are repeated)

算法

Step 1: first we separate out list of all alphabets present in sentence.
Step 2: Convert list of alphabets into set because set contains unique values.
Step 3: if length of set is equal to number of alphabets that means each alphabet occurred once then sentence is heterogram, otherwise not.

示例代码

def stringheterogram(s, n):
   hash = [0] * 26
   for i in range(n):
   if s[i] != ' ':
      if hash[ord(s[i]) - ord('a')] == 0:
      hash[ord(s[i]) - ord('a')] = 1
   else:
   return False
   return True

   # Driven Code
   s = input("Enter the String ::>")
   n = len(s)
print(s,"This string is Heterogram" if stringheterogram(s, n) else "This string is not Heterogram")

输出

Enter the String ::> asd fgh jkl
asd fgh jkl this string is Heterogram

Enter the String ::>asdf asryy
asdf asryy This string is not Heterogram

更新时间:2020 年 6 月 23 日

超过 1K 浏览量

开启你的职业

完成课程即可获得认证

开始学习
广告
© . All rights reserved.