Advertisement
AyrA

Palindrome checker

Jun 18th, 2019
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.11 KB | None | 0 0
  1. #https://redd.it/c1yls0
  2.  
  3.         public static string LongestPalindrome(string input)
  4.         {
  5.             if (input == null || input.Length == 0)
  6.             {
  7.                 //Don't bother doing anything if length is zero
  8.                 return "";
  9.             }
  10.             //Maximum palindrome length so far
  11.             int max = -1;
  12.             //Longest palindrome so far
  13.             string longest = "";
  14.             //Possible palindrome we are checking
  15.             string palindrome;
  16.  
  17.             for (int i = 0; i < input.Length; i++)
  18.             {
  19.                 //Use lastIndexOf as start value of loop
  20.                 for (int j = input.LastIndexOf(input[i]); j > i; j--)
  21.                 {
  22.                     int length = j + 1 - i;
  23.                     //Check max length in the outer condition to avoid substring (it's expensive)
  24.                     if (length > max && input[i] == input[j])
  25.                     {
  26.                         //Substring in C# is (start,length) not (start,end)
  27.                         palindrome = input.Substring(i, length);
  28.                         if (palli(palindrome))
  29.                         {
  30.                             max = length;
  31.                             longest = palindrome;
  32.                             break;
  33.                         }
  34.                     }
  35.                 }
  36.             }
  37.             //Ternery operator: d=a?b:c
  38.             //Classic: if(a){d=b;}else{d=c;}
  39.             return longest.Length > 0 ? longest : input.Substring(0, 1);
  40.         }
  41.  
  42.         //Changed to bool
  43.         private static bool palli(string k)
  44.         {
  45.             char[] str = k.ToCharArray();
  46.  
  47.             int n = k.Length;
  48.             //You don't need to run through the entire string,
  49.             //just the first half (n/2)
  50.             for (int i = 0; i < n / 2; i++)
  51.             {
  52.                 if (str[i] != str[n - i - 1])
  53.                 {
  54.                     //Return failure directly
  55.                     //and don't bother completing the loop
  56.                     return false;
  57.                 }
  58.             }
  59.             return true;
  60.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement