Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #https://redd.it/c1yls0
- public static string LongestPalindrome(string input)
- {
- if (input == null || input.Length == 0)
- {
- //Don't bother doing anything if length is zero
- return "";
- }
- //Maximum palindrome length so far
- int max = -1;
- //Longest palindrome so far
- string longest = "";
- //Possible palindrome we are checking
- string palindrome;
- for (int i = 0; i < input.Length; i++)
- {
- //Use lastIndexOf as start value of loop
- for (int j = input.LastIndexOf(input[i]); j > i; j--)
- {
- int length = j + 1 - i;
- //Check max length in the outer condition to avoid substring (it's expensive)
- if (length > max && input[i] == input[j])
- {
- //Substring in C# is (start,length) not (start,end)
- palindrome = input.Substring(i, length);
- if (palli(palindrome))
- {
- max = length;
- longest = palindrome;
- break;
- }
- }
- }
- }
- //Ternery operator: d=a?b:c
- //Classic: if(a){d=b;}else{d=c;}
- return longest.Length > 0 ? longest : input.Substring(0, 1);
- }
- //Changed to bool
- private static bool palli(string k)
- {
- char[] str = k.ToCharArray();
- int n = k.Length;
- //You don't need to run through the entire string,
- //just the first half (n/2)
- for (int i = 0; i < n / 2; i++)
- {
- if (str[i] != str[n - i - 1])
- {
- //Return failure directly
- //and don't bother completing the loop
- return false;
- }
- }
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement