Last active
March 14, 2021 00:48
-
-
Save jbasinger/c5245eb8fcb7e9c05e4430a95d7aee22 to your computer and use it in GitHub Desktop.
Revisions
-
jbasinger revised this gist
Mar 14, 2021 . 1 changed file with 49 additions and 0 deletions.There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,49 @@ public string LongestPalindrome(string s) { if (s.Length == 0 || s.Length==1) return s; var longestPali = s[0].ToString(); for (var i = 0; i < s.Length; i++) { //Walk backward until you find the same character then start looking for a palindrome for (var j = s.Length - 1; j >= i; j--) { if (s[i] == s[j]) //Potential Palindrome { var len = j - i+1; //If the length is smaller than our current one, why bother! if (len <= longestPali.Length) continue; var isPalindrome = true; var tempPali = new char[len]; for (int front = i, back = j, first = 0, last = len-1; front <= back; front++, back--, first++, last--) { if (s[front] != s[back]) { isPalindrome = false; break; } tempPali[first] = s[front]; tempPali[last] = s[back]; } var newPali = new string(tempPali); if (isPalindrome && newPali.Length > longestPali.Length) { longestPali = newPali; } } } } return longestPali; } -
jbasinger created this gist
Mar 14, 2021 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,17 @@ [Test] public void PalindromeInTheBeginning() { _sut.LongestPalindrome("babad").ShouldBe("bab"); } [Test] public void PalindromeInTheMiddle() { _sut.LongestPalindrome("cbbd").ShouldBe("bb"); } [Test] public void PalindromeAtTheEnd() { _sut.LongestPalindrome("asedad").ShouldBe("dad"); } 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,11 @@ [Test] public void PalindromeIsTheWholeString() { _sut.LongestPalindrome("racecar").ShouldBe("racecar"); } [Test] public void NoPalindromes() { _sut.LongestPalindrome("ab").ShouldBe("a"); }