Last active
March 14, 2021 00:48
-
-
Save jbasinger/c5245eb8fcb7e9c05e4430a95d7aee22 to your computer and use it in GitHub Desktop.
LeetCode Problem 5
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 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; | |
} |
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
[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 characters
[Test] | |
public void PalindromeIsTheWholeString() | |
{ | |
_sut.LongestPalindrome("racecar").ShouldBe("racecar"); | |
} | |
[Test] | |
public void NoPalindromes() | |
{ | |
_sut.LongestPalindrome("ab").ShouldBe("a"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment