📜  Python|使用 OrderedDict() 检查字符串中字符的顺序

📅  最后修改于: 2022-05-13 01:55:20.551000             🧑  作者: Mango

Python|使用 OrderedDict() 检查字符串中字符的顺序

给定一个输入字符串和一个模式,检查输入字符中的字符串是否遵循与模式中存在的字符相同的顺序。假设模式中不会有任何重复的字符。

例子:

Input: 
string = "engineers rock"
pattern = "er";
Output: true
Explanation: 
All 'e' in the input string are before all 'r'.

Input: 
string = "engineers rock"
pattern = "egr";
Output: false
Explanation: 
There are two 'e' after 'g' in the input string.

Input: 
string = "engineers rock"
pattern = "gsr";
Output: false
Explanation:
There are one 'r' before 's' in the input string.

我们已经有解决这个问题的方法,请参考检查字符串是否遵循模式定义的字符顺序 |设置1。这里我们在Python中使用OrderedDict()快速解决了这个问题。方法很简单,

  • 创建一个输入字符串的 OrderedDict,其中仅包含输入字符串的字符作为Key
  • 现在在模式字符串的开头设置一个指针。
  • 现在遍历生成的 OrderedDict 并将键与模式字符串的单个字符匹配,如果键和字符相互匹配,则将指针加 1。
  • 如果模式的指针到达它的结尾,则意味着字符串遵循模式定义的字符顺序,否则不是。
# Function to check if string follows order of 
# characters defined by a pattern 
from collections import OrderedDict 
  
def checkOrder(input, pattern): 
      
    # create empty OrderedDict 
    # output will be like {'a': None,'b': None, 'c': None} 
    dict = OrderedDict.fromkeys(input) 
  
    # traverse generated OrderedDict parallel with 
    # pattern string to check if order of characters 
    # are same or not 
    ptrlen = 0
    for key,value in dict.items(): 
        if (key == pattern[ptrlen]): 
            ptrlen = ptrlen + 1
          
        # check if we have traverse complete 
        # pattern string 
        if (ptrlen == (len(pattern))): 
            return 'true'
  
    # if we come out from for loop that means 
    # order was mismatched 
    return 'false'
  
# Driver program 
if __name__ == "__main__": 
    input = 'engineers rock'
    pattern = 'egr'
    print (checkOrder(input,pattern)) 

输出:

true