简体   繁体   中英

How to find a longest consecutive repeated substring in a string?

In order to de-crypt a message, I need to first find the key. From the given information, I find the key is part of the string:

str = "251220825122082"

We can easily get that the key should be " 2512208 " since the key is supposed to be repeatedly used in encrypting a message. However, I tried many methods and got the answer " 25122082 ", which adds another 2 in the end, but it's just another beginning of the key.

The method I have tried:

  1. regex: String repeated = str.replaceAll("(.+?)\\\\1+", "$1");
  2. LRS Java

These two provide the same answer(" 25122082 ").

Can anyone help me with this problem?

Thank you!

Thanks to @ajb, solved this question by using find() and group().

    String str = "251220825122082";
    Pattern p = Pattern.compile("(.+?)\\1+");
    Matcher m = p.matcher(str);
    while (m.find()) {
        String repeated = m.group(1);
        System.out.println(repeated);
    }

Output: 2512208

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM