📜  Python中第K个非重复字符使用列表理解和OrderedDict

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

Python中第K个非重复字符使用列表理解和OrderedDict

给定一个字符串和一个数字 k,找出字符串中第 k 个不重复的字符。考虑一个带有 lacs字符和一个小字符集的大输入字符串。如何通过只遍历输入字符串一次来找到字符?

例子:

Input : str = geeksforgeeks, k = 3
Output : r
First non-repeating character is f,
second is o and third is r.

Input : str = geeksforgeeks, k = 2
Output : o

Input : str = geeksforgeeks, k = 4
Output : Less than k non-repeating
         characters in input.

此问题已有解决方案,请参考链接。我们可以使用 List Comprehension 和 OrderedDict 在Python中快速解决这个问题。

# Function to find k'th non repeating character 
# in string 
from collections import OrderedDict 
  
def kthRepeating(input,k): 
  
    # OrderedDict returns a dictionary data 
        # structure having characters of input 
    # string as keys in the same order they 
        # were inserted and 0 as their default value 
    dict=OrderedDict.fromkeys(input,0) 
  
    # now traverse input string to calculate 
        # frequency of each character 
    for ch in input: 
        dict[ch]+=1
  
    # now extract list of all keys whose value 
        # is 1 from dict Ordered Dictionary 
    nonRepeatDict = [key for (key,value) in dict.items() if value==1] 
      
    # now return (k-1)th character from above list 
    if len(nonRepeatDict) < k: 
        return 'Less than k non-repeating characters in input.' 
    else: 
        return nonRepeatDict[k-1] 
  
# Driver function 
if __name__ == "__main__": 
    input = "geeksforgeeks"
    k = 3
    print (kthRepeating(input, k)) 

输出:

r