Tech Qu: Find all palindromes in a string
Wikipedia: A palindrome is a word, phrase, number or other sequence of units that can be read the same way in either direction (the adjustment of punctuation and spaces between words is generally permitted).
First, we need to define the minimum length to qualify as a palindrome. We’ll call this minLength.
- First filter non-letters and convert everything to upper case.
- Create an array of characters.
- Walk all possible strings of sufficient length and determine it they are matches.
- We avoid using string function to obtain good performance and small memory size.
- No recursions or functions calls
Function
- public static int Palindromes(string a, int minLength)
- {
- int result = 0;
- var letters = a.ToUpper().ToCharArray();
- // remove spaces etc, leave only A-Z
- var filtered = new StringBuilder();
- foreach (var t in letters)
- {
- if (t >= 'A' && t <= 'Z')
- {
- filtered.Append(t);
- }
- }
- letters = filtered.ToString().ToCharArray();
- if (letters.Length < minLength)
- {
- return 0;
- }
- for (var palindromeLength = minLength; palindromeLength <= letters.Length; palindromeLength++)
- {
- for (var startat = 0; startat < letters.Length - palindromeLength+1; startat++)
- {
- bool isP = true;
- var sIndex = startat;
- var eIndex = startat + palindromeLength-1;
- while (sIndex < eIndex)
- {
- if (letters[sIndex] == letters[eIndex])
- {
- sIndex++;
- eIndex--;
- }
- else
- {
- isP = false;
- break;
- }
- }
- if (isP)
- {
- Console.WriteLine(filtered.ToString().Substring(startat, palindromeLength));
- result++;
- }
- }
- }
- return result;
- }
The unit test is simple and uses one known palindrome and random letters.
Unit Test
- string[] testcases = { "Able WaS I sAw ELBA!","ABCBA", "ABACADAEAF"};
- foreach(var test in testcases)
- {
- Console.WriteLine(string.Format("{0} --> {1}",test, Questions.Palindromes(test,3)));
- }
The test run allows us to confirm correct operation.
Solve the test without iterations. Hint: regular expressions.
ReplyDelete