Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a repeated pattern in a string

How can I find a repeated pattern in a string? For example, if the input file were

AAAAAAAAA
ABABAB
ABCAB
ABAb

it would output:

A
AB
ABCAB
ABAb
like image 660
jwaang Avatar asked Feb 22 '14 22:02

jwaang


People also ask

How do I find a repeating pattern in a string?

Algorithm. Construct a string pattern adding the input string str twice. Remove the first and last characters in the pattern. Find for str in the pattern, if the match is found return True else return False.

What is an example of a repeated pattern?

The most important term is congruent which is equivalent to saying that a repeating pattern has identical units of repeat. Other useful terms are rectangle and parallel. Most repeating patterns in the environment occur in manufactured objects. Some examples are tiles, pavers, windows, zebra crossings and railway lines.

How do you find a repeating substring in Python?

This problem can also be solved using the fact that we can search for root string after adding a string and checking the root string in this string except last and first character, represents the string is repeating itself.


2 Answers

If you use regex, you only need one line:

String repeated = str.replaceAll("(.+?)\\1+", "$1");

Breaking down the regex (.+?)\1:

  • (.+?) means "at least one character, but as few as possible, captured as group 1"
  • \1 means "the same character(s) as group 1

Here's some test code:

String[] strs = {"AAAAAAAAA", "ABABAB", "ABCAB", "ABAb"};
for (String str : strs) {
    String repeated = str.replaceAll("(.+?)\\1+", "$1");
    System.out.println(repeated);
}

Output:

A
AB
ABCAB
ABAb
like image 170
Bohemian Avatar answered Oct 01 '22 16:10

Bohemian


This outputs what you ask for - the regex can probably be improved to avoid the loop but I can't manage to fix it...

public static void main(String[] args) {
    List<String> inputs = Arrays.asList("AAAAAAAAA", "ABABAB", "ABCAB", "ABAb");
    for (String s : inputs) System.out.println(findPattern(s));
}

private static String findPattern(String s) {
    String output = s;
    String temp;
    while (true) {
        temp = output.replaceAll("(.+)\\1", "$1");
        if (temp.equals(output)) break;
        output = temp;
    }
    return output;
}
like image 25
assylias Avatar answered Oct 01 '22 16:10

assylias