forked from TheRenegadeCoder/sample-programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add LongestPalindromicSubstring in C# (TheRenegadeCoder#3989)
- Loading branch information
1 parent
7c09559
commit 4ce60e7
Showing
1 changed file
with
71 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
using System; | ||
using System.Text.RegularExpressions; | ||
|
||
namespace SamplePrograms | ||
{ | ||
public class LongestPalindromicSubstring | ||
{ | ||
public static void Main(string[] args) | ||
{ | ||
string input = string.Join(" ", args); | ||
Console.WriteLine(LongestPalindrome(input)); | ||
} | ||
|
||
public static string LongestPalindrome(string input) | ||
{ | ||
if (string.IsNullOrEmpty(input) || !ContainsPalindrome(input)) | ||
{ | ||
return "Usage: please provide a string that contains at least one palindrome"; | ||
} | ||
|
||
int start = 0; | ||
int end = 0; | ||
|
||
for (int i = 0; i < input.Length; i++) | ||
{ | ||
int lengthOne = ExpandAroundCenter(input, i, i); | ||
int lengthTwo = ExpandAroundCenter(input, i, i + 1); | ||
int length = Math.Max(lengthOne, lengthTwo); | ||
|
||
if (length > end - start) | ||
{ | ||
start = i - (length - 1) / 2; | ||
end = i + length / 2; | ||
} | ||
} | ||
return input.Substring(start, end - start + 1); | ||
} | ||
|
||
private static int ExpandAroundCenter(string input, int left, int right) | ||
{ | ||
while (left >= 0 && right < input.Length && input[left] == input[right]) | ||
{ | ||
left--; | ||
right++; | ||
} | ||
return right - left - 1; | ||
} | ||
|
||
private static bool ContainsPalindrome(string input) | ||
{ | ||
string[] words = input.Split(' '); | ||
foreach (string word in words) | ||
{ | ||
if (word.Length > 1 && word == Reverse(word)) | ||
{ | ||
return true; | ||
} | ||
} | ||
|
||
string cleanedInput = input.Replace(" ", ""); | ||
return cleanedInput.Length > 1 && cleanedInput == Reverse(cleanedInput); | ||
} | ||
|
||
private static string Reverse(string input) | ||
{ | ||
char[] charArray = input.ToCharArray(); | ||
Array.Reverse(charArray); | ||
return new string(charArray); | ||
} | ||
} | ||
} |