Algorithm exercise: Find the longest repeating substring of a string (Java implementation)

Source: Internet
Author: User

1. Find the longest repeating substring of a string

For example: AAAAAAAAABBBBCCCAAASSSCVVV the longest repeating substring inside this is AAAAAAAAA

Algorithmic thinking: Algorithmic Time complexity (O (n))

1. Turn this string into a char array first;

2. Iterate over this char array

3. Compares the characters of i-1 and I in a char array, if not equal, intercepts the string length, compares it, and replaces it if it is longer than the existing length, or does nothing

Algorithm implementation: (Java Implementation)

    private static string Resubstr (String str) {        /**         * Set Variable         * Start: Start         * End: End         * Maxstart: Oldest string start position         * Maxend: Oldest string End position         */        int start=0,end=1,maxstart=0,maxend=1;        char[] chars = Str.tochararray ();        for (int i = 1; i < chars.length; i++) {            //To determine if not equal, the length of the calculator if            (Chars[i-1]!=chars[i]) {
Sets the end position of its repeating substring end=i; substring length int len = End-start; The substring length is greater than the existing maximum substring length if (Len > (Maxend-maxstart)) { //is assigned Maxstart = start; Maxend = end; } Start intercept position for end position start = end;} } Intercept string return str.substring (maxstart,maxend); }

  

Algorithm exercise: Find the longest repeating substring of a string (Java implementation)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.