Created
August 19, 2016 23:42
-
-
Save jianminchen/71421f776948086fd653e441725b3732 to your computer and use it in GitHub Desktop.
Leetcode 125 - valid palindrome - 6th practice - follow the flow of real processing - skip left/right if need, comparison failed, or continue to compare
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
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: | |
* | |
* 1. skip left if it is not alphabetic char or number -> a while loop | |
* 2. skip right if it is not alphabetic char or number -> a while loop | |
* 3. if the left and right are nto equal, return false | |
* 4. left pointer increments one, right pointer decrements one. | |
* | |
* The code is matching the above steps. | |
*/ | |
public static bool isPalindrome(string s) | |
{ | |
if (s == null || s.Length == 0) | |
return true; | |
int left = 0; | |
int right = s.Length - 1; | |
while (left < right) | |
{ | |
// skip left char | |
while (left < right && !isAlnum(s[left])) | |
left++; | |
// skip right char | |
while (left < right && !isAlnum(s[right])) | |
right--; | |
if (toUpper(s[left]) != toUpper(s[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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment