- Add some negative/edge test cases.
- Convert to recursive solution.
- I find multiple return statements tricky to follow.
- This problem lends itself nicely to recursion since we can know the call stack size ahead of time. It is also tail recursive, if C# supports that?
using System; class Palindrome { public static bool Check(string word){ word = word.ToUpper(); return Check(word, 0); } private static bool Check(string word, int index) { var reverseIndex = word.Length - 1 - index; return reverseIndex <= index ? true : word[index] == word[reverseIndex] ? Check(word, index + 1) : false; } }
- using System;
- class Palindrome
- {
- public static bool Check(string word){
- word = word.ToUpper();
for(int i = 0; i < word.Length / 2; i++){if(word[i] != word[word.Length - 1 - i]){return false;}}return true;- return Check(word, 0);
- }
- private static bool Check(string word, int index) {
- var reverseIndex = word.Length - 1 - index;
- return reverseIndex <= index
- ? true
- : word[index] == word[reverseIndex]
- ? Check(word, index + 1)
- : false;
- }
- }
namespace Solution { using NUnit.Framework; using System; [TestFixture] public class SolutionTest { [Test] public void MyTest() { Assert.AreEqual(true, Palindrome.Check("a")); Assert.AreEqual(true, Palindrome.Check("MOM")); Assert.AreEqual(true, Palindrome.Check("kAyaK")); Assert.AreEqual(true, Palindrome.Check("12344321")); Assert.AreEqual(false, Palindrome.Check("2454321")); Assert.AreEqual(false, Palindrome.Check("123554321")); } } }
- namespace Solution {
- using NUnit.Framework;
- using System;
// TODO: Replace examples and use TDD development by writing your own tests- [TestFixture]
- public class SolutionTest
- {
- [Test]
- public void MyTest()
- {
- Assert.AreEqual(true, Palindrome.Check("a"));
- Assert.AreEqual(true, Palindrome.Check("MOM"));
- Assert.AreEqual(true, Palindrome.Check("kAyaK"));
Assert.AreEqual(true, Palindrome.Check("123454321"));- Assert.AreEqual(true, Palindrome.Check("12344321"));
- Assert.AreEqual(false, Palindrome.Check("2454321"));
- Assert.AreEqual(false, Palindrome.Check("123554321"));
- }
- }
- }