Python 中的古代宇航员理论

pythonserver side programmingprogramming更新于 2025/11/3 14:36:17

假设我们有一个字符串字典,该字典表示古代宇航员字典的部分字典顺序。因此,如果我们有一个字符串 s,我们必须根据这本古老的宇航员字典检查它是否是按字典顺序排序的字符串。

因此,如果输入为 dictionary = "bdc", s = "bbbb h ddd i cccc",则输出将为 True

要解决这个问题,我们将遵循以下步骤 −

  • l := size of astro_dict

  • 如果 l 与 0 相同,则

    • 返回 True

  • i := 0

  • 对于 s 中的每个字符 c,执行

    • 如果 c 在astro_dict,然后

      • 当 i < l 且 astro_dict[i] 不是 c 时,执行

        • i := i + 1

      • 如果 i >= l 或 astro_dict[i] 不是 c,则

        • 返回 False

  • 返回 True

让我们看看以下实现以获得更好的理解 −

示例

class Solution:
   def solve(self, astro_dict, s):
      l = len(astro_dict)
      if l == 0:
         return True
      i = 0
      for c in s:
         if c in astro_dict:
            while i < l and astro_dict[i] != c:
               i += 1
            if i >= l or astro_dict[i] != c:
               return False
      return True
ob = Solution()
print(ob.solve("bdc","bbbb h ddd i cccc"))

输入

"bdc","bbbb h ddd i cccc"

输出

True

相关文章


有用资源