Created
July 22, 2013 23:10
-
-
Save riyadparvez/6058526 to your computer and use it in GitHub Desktop.
Implements finding longest palindrome in a string using dynamic programming in C#.
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
| public static string LongestPalindrome(string str) | |
| { | |
| var chars = str.ToCharArray(); | |
| var dp = new bool[chars.Length, chars.Length]; | |
| int longestBegin = 0; | |
| int maxLength = 1; | |
| for (int i = 0; i < chars.Length; i++) | |
| { | |
| dp[i, i] = true; | |
| } | |
| for (int i = 0; i < chars.Length-1; i++) | |
| { | |
| if(chars[i] == chars[i+1]) | |
| { | |
| dp[i, i+1] = true; | |
| longestBegin = i; | |
| maxLength = 2; | |
| } | |
| } | |
| for (int length = 3; length <= chars.Length; length++) | |
| { | |
| for (int i = 0; i < chars.Length-length+1; i++) | |
| { | |
| int j = i+length-1; | |
| if(chars[i] == chars[j] && dp[i+1, j-1]) | |
| { | |
| dp[i, j] = true; | |
| if(maxLength < (j-i)) | |
| { | |
| maxLength = j - i; | |
| longestBegin = i; | |
| } | |
| } | |
| } | |
| } | |
| return str.Substring(longestBegin, maxLength); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment