问题描述
我的一个朋友刚做了他的采访在谷歌,得到了拒绝,因为他不能给解决这个问题。
A friend of mine just had his interview at Google and got rejected because he couldn't give a solution to this question.
我有几天我自己的面试,似乎无法想出一个办法来解决它。
I have my own interview in a couple of days and can't seem to figure out a way to solve it.
下面的问题:
正在给定的图案,如[A B A B]。您也给予了 字符串,例如redblueredblue。我需要编写一个程序,告诉 是否该字符串的给定模式或没有。
举几个例子:
模式:[利群]字符串:catdogdogcat返回1
Pattern: [a b b a] String: catdogdogcat returns 1
模式:ABAB]字符串:redblueredblue返回1
Pattern: [a b a b] String: redblueredblue returns 1
模式:[利群]字符串:redblueredblue返回0
Pattern: [a b b a] String: redblueredblue returns 0
我想到了几个办法,想获得在图案独特的字符数,然后找到该字符串的许多独特的子然后使用一个HashMap的模式相比较。但是,原来是一个问题,如果一个子串为b的一部分。
I thought of a few approaches, like getting the number of unique characters in the pattern and then finding that many unique substrings of the string then comparing with the pattern using a hashmap. However, that turns out to be a problem if the substring of a is a part of b.
这将会是真正伟大如果你们可以帮助我吧。 :)
It'd be really great if any of you could help me out with it. :)
更新:
新增信息:可以有任意数量的模式(亚利桑那州)的字符。两个字符不会再present相同的子字符串。此外,一个字符不能再present一个空字符串。
Added Info: There can be any number of characters in the pattern (a-z). Two characters won't represent the same substring. Also, a character can't represent an empty string.
推荐答案
难道你只需要翻译使用反向引用的模式应用到正则表达式,即是这样的(Python 3中与装载的重模块):
Don't you just need to translate the pattern to a regexp using backreferences, i.e. something like this (Python 3 with the "re" module loaded):
>>> print(re.match('(.+)(.+)\\2\\1', 'catdogdogcat'))
<_sre.SRE_Match object; span=(0, 12), match='catdogdogcat'>
>>> print(re.match('(.+)(.+)\\1\\2', 'redblueredblue'))
<_sre.SRE_Match object; span=(0, 14), match='redblueredblue'>
>>> print(re.match('(.+)(.+)\\2\\1', 'redblueredblue'))
None
的正则表达式看起来pretty的微不足道的产生。如果需要支持超过9 backrefs,你可以使用命名组 - 见href="https://docs.python.org/3.4/library/re.html"> Python的正则表达式文档的
这篇关于检查是否给定的字符串遵循特定的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!