Check if the string repeats itself

By   Tewodros   Date Posted: Feb. 23, 2022  Hits: 900   Category:  Algorithm   Total Comment: 0             A+ A-


side

Check if the string repeats itself any number of times and return true if it does. Otherwise return false

Examples:

abaaba  True

ababa  False

ababab True

aaaaa True

Solution:

 

 

  public static bool RepeatedSubstringPattern(string s)

       {

           int n = s.Length;

           StringBuilder sb = new StringBuilder();

           for (int i = n / 2; i >= 1; i--)

           {

               if (n % i == 0)

               {

                   for (int j = 0; j < n / i; j++)

                   {

                       sb.Append(s.Substring(0, i));

                   }

                   if (sb.ToString().Equals(s)) return true;

                   sb.Clear();

               }

           }

 

           return false;

       }


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* vtbbcd

Back to Top