模式匹配:将String与模式匹配

时间:2022-09-13 07:44:05

I was trying to match a pattern within a string. I am running out of ideas how to do this in Java with good time complexity.

我试图匹配字符串中的模式。我已经没有想法如何在Java中做到这一点,时间复杂度很高。

No its not a simple regex matching (but loved to be proved wrong)

不,它不是一个简单的正则表达式匹配(但被证明是错误的)

What I am trying is,

我在想的是,

Pattern : "1221" (Means 1 word repeat once, 2nd word repeat twice, last word is same as first word)

模式:“1221”(表示1个字重复一次,第2个字重复两次,最后一个字与第一个字相同)

Valid Input: "aabbbbbbaa" (aa occurs at the beginning and at end, while middle portion is occupied by bbb repeating twice)

有效输入:“aabbbbbbaa”(aa出现在开头和结尾,而中间部分被bbb重复两次)

I tried the following approaches but failed miserably

我尝试了以下方法,但失败了

  • I tried to loop input with the pattern. But that did not solve the problem, although with more loops I can achieve it, but it increases the time complexity exponentially.
  • 我试图用模式循环输入。但这并没有解决问题,虽然我可以实现更多的循环,但它会以指数方式增加时间复杂度。

  • Tried recursion and again no use.
  • 尝试递归,再次没有用。

What other approaches can I try?

我可以尝试其他什么方法?

I think Dynamic programming might be the answer, but I am not able to determine the terminating condition.

我认为动态编程可能是答案,但我无法确定终止条件。

Any help would be appreciated.

任何帮助,将不胜感激。

1 个解决方案

#1


2  

You can use simple regex, e.g.:

你可以使用简单的正则表达式,例如:

^(.+)(.+)\2\1$

It does exactly what u want:

它完全符合您的要求:

模式匹配:将String与模式匹配

#1


2  

You can use simple regex, e.g.:

你可以使用简单的正则表达式,例如:

^(.+)(.+)\2\1$

It does exactly what u want:

它完全符合您的要求:

模式匹配:将String与模式匹配