ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

在Python中搜索子字符串的字符排列

2019-10-11 05:56:21  阅读:135  来源: 互联网

标签:python string regex permutation


我正在尝试从一行文本中提取字符串的出现及其字符的所有排列.

例如,我需要从以下字符串s中提取字符串t =’ABC’及其所有排列:’ABC’,’CAB’,’BCA’,’BAC’,’CBA’:

s = 'ABCXABCXXACXXBACXXBCA'

结果为:ABC,ABC,BAC,BCA

字符串t可以是任何长度,并且可以包含[A-Z],[a-z]和[0-9]中的任何字符

有没有一种方法可以通过在Python中使用正则表达式来获得结果?

我知道我可以只构建所有排列的列表,然后对列表中的所有项目进行单独搜索,但是我想知道正则表达式是否可以更紧凑,更快速地提供结果.

解决方法:

让我来画一个解决问题的算法.正则表达式不是要解决的问题.

此解决方案维护一个滑动窗口,并使用t的频率检查窗口中字符的频率.

下面是该算法的伪代码:

function searchPermutation(inpStr, t):
    // You may want to check t against the regex ^[A-Za-z0-9]+$here

    // Do a frequency counting of character in t
    // For example, t = 'aABBCCC'
    // Then freq = { 'A': 1, 'B': 2, 'C': 3, 'a': 1 }
    freq = frequency(t)

    // Create an empty dict
    window = {}
    // Number of characters in window
    count = 0
    // List of matches
    result = []

    for (i = 0; i < inpStr.length; i++):
        // If the current character is a character in t
        if inpStr[i] in freq:
            // Add the character at current position
            window[inpStr[i]]++

            // If number of character in window is equal to length of t
            if count == t.length:
                // Remove the character at the end of the window
                window[inpStr[i - t.length]]--
                // The count is kept the same here
            else: // Otherwise, increase the count
                count++

            // If all frequencies in window is the same as freq
            if count == t.length and window == freq:
                // Add to the result a match at (i - t.length + 1, i + 1)
                // We can retrieve the string later with substring
                result.append((i - t.length + 1, i + 1))

                // Reset the window and count (prevent overlapping match)
                // Remove the 2 line below if you want to include overlapping match
                window = {}
                count = 0
        else: // If current character not in t
            // Reset the window and count
            window = {}
            count = 0

    return result

这应该解决任何t的一般问题.

标签:python,string,regex,permutation
来源: https://codeday.me/bug/20191011/1890511.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有