Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created August 22, 2016 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/765a169c1f4e3b1d1fc66f3deca16410 to your computer and use it in GitHub Desktop.
Save jianminchen/765a169c1f4e3b1d1fc66f3deca16410 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Leetcode125_IsPalindrome
{
class Program
{
/*
* Leetcode 125: is palindrome
*
* blog to read:
* http://blog.csdn.net/nomasp/article/details/50623165
*/
static void Main(string[] args)
{
bool test = isPalindrome("Aa");
bool test2 = isPalindrome("Ab%Ba");
bool test3 = isPalindrome("B%1*1b");
}
/*
* Function design:
*
* study the code:
* https://github.com/jianminchen/leetcode-1/blob/master/algorithms/validPalindrome/validPalindrome.cpp
*
* Time complexity:
* O(N)
*
* Extract a function called removeNoise(),
* therefore, this function is much simple. No dirty business about sorting out
* at least 4 cases, if/else etc.
* 1. easy to avoid bugs in writing
* 2. 80% easy to do static analysis
* 3. time to write, test is 20% of orginal one - practice #9
*
* https://gist.github.com/jianminchen/ce79fbd9c3c97b628d8857f55e684aab
*
*/
public static bool isPalindrome(string s)
{
if (s == null || s.Length == 0)
return true;
string s1 = removeNoise(s);
int left = 0;
int right = s1.Length - 1;
while (left < right)
{
if (s1[left] != s1[right])
return false;
left++;
right--;
}
return true;
}
/*
* a-z
* A-Z
* 0-9
*/
private static bool isAlnum(char c)
{
const int SIZE = 26;
int[] arr = new int[] { c - 'a', c - 'A', c - '0' };
// is A-Z or a-z or 0 -9
if ((arr[0] >= 0 && arr[0] < SIZE) ||
(arr[1] >= 0 && arr[1] < SIZE) ||
(arr[2] >= 0 && arr[2] <= 9))
return true;
return false;
}
/*
*
*/
private static char toUpper(char c)
{
int no = c - 'a';
if (no >= 0 && no < 26)
return (char)('A' + no);
else
return c;
}
/*
* Time complexity:
* O(N)
*
* output string to uppercase if it is alphabetic char.
*/
private static string removeNoise(string s)
{
StringBuilder sb = new StringBuilder();
foreach (char c in s)
{
if (isAlnum(c))
sb.Append(toUpper(c));
}
return sb.ToString();
}
}
}
@jianminchen
Copy link
Author

Practice highlights:

  1. Extract one more function from isPalindrome - called removeNoise, same time complexity of O(N).
  2. The code is much simple and easy to compare to previous 1 - 9 practice, reduce 80% complexity of static analysis, test cases,
    validation of ++, -- of left/ right. When to do both, one side only.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment