在Python中搜索子字符串的字符排列
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了在Python中搜索子字符串的字符排列,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1859字,纯文字阅读大概需要3分钟。
内容图文
![在Python中搜索子字符串的字符排列](/upload/InfoBanner/zyjiaocheng/694/724015c4111a4184a18c045e63e9684b.jpg)
我正在尝试从一行文本中提取字符串的出现及其字符的所有排列.
例如,我需要从以下字符串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中搜索子字符串的字符排列全部内容,希望文章能够帮你解决在Python中搜索子字符串的字符排列所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。