Created
July 23, 2013 05:22
-
-
Save riyadparvez/6060040 to your computer and use it in GitHub Desktop.
Finds longest palindrome in a string in O(n*n) time and O(1) space.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| private static string Expand(string str, int c1, int c2) | |
| { | |
| int left = c1; | |
| int right = c2; | |
| while (left >= 0 && right < str.Length && str[left] == str[right]) | |
| { | |
| left--; | |
| right++; | |
| } | |
| return str.Substring(left+1, right-left-1); | |
| } | |
| public static string LongestPalindrome(string str) | |
| { | |
| var chars = str.ToCharArray(); | |
| var dp = new bool[chars.Length, chars.Length]; | |
| string longest; | |
| for (int i = 0; i < str.Length-1; i++) | |
| { | |
| string str1 = Expand(str, i, i); | |
| if(str1.Length >= longest.Length) | |
| { | |
| longest = str1; | |
| } | |
| string str2 = Expand(str, i, i+1); | |
| if (str2.Length >= longest.Length) | |
| { | |
| longest = str2; | |
| } | |
| } | |
| return longest; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment