Advertisement
ivandrofly

hackerrank: Super Reduced String

Feb 3rd, 2024 (edited)
1,309
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.00 KB | None | 1 0
  1. static string SuperReducedString(string s)
  2. {
  3.     // Convert the string to a character array for easier manipulation
  4.     char[] chars = s.ToCharArray();
  5.     int length = chars.Length;
  6.  
  7.     // Loop through the characters, checking for adjacent duplicates
  8.     for (int i = 0; i < length - 1; i++)
  9.     {
  10.         // If adjacent characters are the same, remove them and adjust the array
  11.         if (chars[i] == chars[i + 1])
  12.         {
  13.             // Shift the characters after the adjacent duplicates to the left
  14.             for (int j = i + 2; j < length; j++)
  15.             {
  16.                 chars[j - 2] = chars[j];
  17.             }
  18.  
  19.             // Adjust the length and reset the index
  20.             length -= 2;
  21.             i = -1; // Start over after removing adjacent duplicates
  22.         }
  23.     }
  24.  
  25.     // If the final string is empty, return "Empty String", otherwise return the reduced string
  26.     if (length == 0)
  27.         return "Empty String";
  28.     else
  29.         return new string(chars, 0, length);
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement