Facebook Interview Question
Software EngineersCountry: United States
Interview Type: Phone Interview
Good answer. Just one point. You should compare a and b with equals not "==" since a and b are Character pointers not char variables. or you could just use valA and valB also since you are comparing in the begining you could simplify the if statment by use chain if else-if statements like below:
if(valA < 0 || valA >= 26) {
i++;
}else if(valB < 0 || valB >= 26) {
j--;
}else if( valA != valB) {
return false;
} else{
i++;
j--;
}
@amirtar in java char is a primitive type, making comparison with "==" completely safe.
The above solution is not working for "1212"...
Try this.....
public class Test{
public static void main(String [] args)
{
if (isPalindrome("1221"))
System.out.println("true");
else
System.out.println("false");
}
public static boolean isPalindrome(String str){
int stringLength=str.length();
if (stringLength==1)
return true;
int i=0;
int j=stringLength-1;
while (i<j){
while (!((Character.toLowerCase(str.charAt(i))>=97 && Character.toLowerCase(str.charAt(i))<=122) || (Character.toLowerCase(str.charAt(i))>=48 &&Character.toLowerCase(str.charAt(i))<=57)))
i++;
while (!((Character.toLowerCase(str.charAt(j))>=97 && Character.toLowerCase(str.charAt(j))<=122) || (Character.toLowerCase(str.charAt(j))>=48 &&Character.toLowerCase(str.charAt(j))<=57)))
j--;
if(Character.toLowerCase(str.charAt(i))!=Character.toLowerCase(str.charAt(j)))
return false;
i++;
j--;
}
return true;
}
}
Here is C++ version:
bool IsAlphabet(char c)
{
return ((c >='a' && c<='z')||(c>='A' &&c<='Z'));
}
bool IsSame(char s , char d)
{
int lowbase_a = s-'a';
int upperbase_a = s-'A';
int lowbase_d = d-'a';
int upperbase_d = d - 'A';
return ((lowbase_a == lowbase_d) ||(upperbase_a == upperbase_d) || (lowbase_a == upperbase_d) || (upperbase_a) == (lowbase_d));
}
bool IsPanlindrome(const char * str, int length)
{
int s = 0;
int e = length;
while (s < e)
{
if (!IsAlphabet(str[s]))
{
s++;
continue;
}
if (!IsAlphabet(str[e]))
{
e--;
continue;
}
if (IsSame(str[s], str[e]))
{
s++;
e--;
} else
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(isPal("A man, a plan, a canal, Panama!"));
System.out.println(isPal("Madam I'm Adam"));
}
public static boolean isPal(String rest) {
if (rest.trim().length() < 2) return true;
char first = getCharOrSkip(rest, 0, 1);
char last = getCharOrSkip(rest, rest.length()-1, -1);
int firstPos = rest.indexOf(first);
int lastPost = rest.lastIndexOf(String.valueOf(last));
return firstPos == lastPost || (toLower(first) == toLower(last) && isPal(rest.substring(firstPos+1, lastPost)));
}
public static char getCharOrSkip(String str, int pos, int direction) {
char c = str.charAt(pos);
return ((c >= 'A' && c<= 'Z') || (c >= 'a' && c <= 'z')) ? c : getCharOrSkip(str, pos + direction, direction);
}
public static char toLower(char c) {
return (c >= 'a') ? (char) (c - 32) : c;
}
In C#
static void Main(string[] args)
{
PalindromeCheck("A man, a plan, a canal, Panama!");
Console.ReadLine();
}
static void PalindromeCheck(String palindrom)
{
int j=palindrom.Length-1;
int i=0;
bool isPalindrom = true;
do
{
char c1 = Char.ToLower(palindrom[i]);
char c2 = Char.ToLower(palindrom[j]);
while (!Char.IsLetter(c1) && !Char.IsNumber(c1))
{
i++;
c1 = Char.ToLower(palindrom[i]);
}
while (!Char.IsLetter(c2) && !Char.IsNumber(c2))
{
j--;
c2 = Char.ToLower(palindrom[j]);
}
i++;
j--;
if (c1 != c2) { isPalindrom = false; }
} while (i<j && isPalindrom==true);
Console.WriteLine("Is Palindrom?: " + isPalindrom);
}
}
// Ignores everything except alpha characters
bool isPalindromeAlpha(char* inputString, char* startPos, char* endPos)
{
bool isPalindrome = true;
char charToCompare1 = '\0';
char charToCompare2 = '\0';
while (startPos < endPos)
{
// Skip over characters that are not letters
while ( ((*startPos < 'a' || *startPos > 'z') && (*startPos < 'A' || *startPos > 'Z')) && startPos < endPos)
{
startPos++;
}
while (((*endPos < 'a' || *endPos > 'z') && (*endPos < 'A' || *endPos > 'Z')) && endPos > startPos)
{
endPos--;
}
// Make all letters lowercase
charToCompare1 = *startPos;
if (charToCompare1 >= 'A' && charToCompare1 <= 'Z')
{
charToCompare1 = 'a' + (charToCompare1 % 'A');
}
charToCompare2 = *endPos;
if (charToCompare2 >= 'A' && charToCompare2 <= 'Z')
{
charToCompare2 = 'a' + (charToCompare2 % 'A');
}
if (charToCompare1 != charToCompare2)
{
isPalindrome = false;
break;
}
else
{
startPos++;
endPos--;
}
}
return isPalindrome;
}
int _tmain(int argc, _TCHAR* argv[])
{
char inputString[] = "A man, a plan, a canal, Panama!";
//char inputString[] = "#!@$% Ab !@%!@ B !%@!%!@% a 1 % !@% C !@%!@% a 1 % !@% B 1 % !@% b @!#)(*) A ";
cout << inputString << (isPalindromeAlpha(inputString, inputString, inputString + strlen(inputString) - 1) ? " is " : " is not ") << "a palindrome";
return 0;
}
This is my two cents:
public static void main(String[] args) {
System.out.println(isPal("A man, a plan, a canal, Panama!"));
System.out.println(isPal("Madam I'm Adam"));
System.out.println(isPal("aba"));
System.out.println(isPal("#!@$% Ab !@%!@ B !%@!%!@% a 1%!@% C !@%!@% a 1%!@% B 1%!@% b @!#)(*) A"));
System.out.println(isPal("TEST"));
}
public static boolean isPal(String rest) {
if (rest.trim().length() < 2) return true;
char first = getCharOrSkip(rest, 0, 1);
char last = getCharOrSkip(rest, rest.length()-1, -1);
int firstPos = rest.indexOf(first);
int lastPost = rest.lastIndexOf(String.valueOf(last));
return firstPos == lastPost || (toLower(first) == toLower(last) && isPal(rest.substring(firstPos+1, lastPost)));
}
public static char getCharOrSkip(String str, int pos, int direction) {
char c = str.charAt(pos);
return ((c >= 'A' && c<= 'Z') || (c >= 'a' && c <= 'z')) ? c : getCharOrSkip(str, pos + direction, direction);
}
public static char toLower(char c) {
return (c >= 'a') ? (char) (c - 32) : c;
}
def checkPalindrome(string):
startindex = 0
endindex = len(string) - 1
isPalindrome = True
while True:
if endindex <= startindex:
break
startchar = string[startindex]
endchar = string[endindex]
if not startchar.isalpha():
startindex += 1
continue
if not endchar.isalpha():
endindex -= 1
continue
if startchar.lower() != endchar.lower():
isPalindrome = False
break
else:
startindex += 1
endindex -= 1
return isPalindrome
print checkPalindrome('A man, a plan, a canal, Panama!')
public static boolean isPalindromeDev(String input) {
int i = 0, j = input.length()-1;
char[] chars = input.toLowerCase().toCharArray();
while( i < j ) {
while((chars[i] - 'a') < 0 || (chars[i] - 'a') > 25)
i++;
while((chars[j] - 'a') < 0 || (chars[j] - 'a') > 25)
j--;
if(chars[i] != chars[j]) {
return false;
}
i++;
j--;
}
return true;
}
public static boolean isPalindrome(String str){
return removeSpecialChars(str).toString().equalsIgnoreCase(removeSpecialChars(str).reverse().toString());
}
public static StringBuilder removeSpecialChars(String str){
StringBuilder sb = new StringBuilder();
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
if(((chars[i] >= 'A' && chars[i]<= 'Z') || (chars[i] >= 'a' && chars[i] <= 'z')) ){
sb.append(chars[i]);
}
}
return sb;
}
public static boolean isPalindrome(String str){
return removeSpecialChars(str).toString().equalsIgnoreCase(removeSpecialChars(str).reverse().toString());
}
public static StringBuilder removeSpecialChars(String str){
StringBuilder sb = new StringBuilder();
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
if(((chars[i] >= 'A' && chars[i]<= 'Z') || (chars[i] >= 'a' && chars[i] <= 'z')) ){
sb.append(chars[i]);
}
}
return sb;
}
public static bool IsPalindrome(string source, bool alphaNumericOnly = true)
{
if (string.IsNullOrEmpty(source))
{
return false;
}
var endPointer = source.Length-1;
var startPointer = 0;
while (startPointer < endPointer)
{
//get the char ascii and minus 'a' value - so that we get 0 to 26 alphabets
//ignore case of course.
var valA = Char.ToLower(source[startPointer]) - 'a';
var valB = Char.ToLower(source[endPointer]) - 'a';
if (valA < 0 || valA > 26)
{
startPointer++;
}
else if (valB < 0 || valB > 26)
{
endPointer--;
}
else if (valA != valB)
{
return false;
}
else {
startPointer++;
endPointer--;
}
}
return true;
}
public static bool IsPalindrome(string source, bool alphaNumericOnly = true)
{
if (string.IsNullOrEmpty(source))
{
return false;
}
var endPointer = source.Length-1;
var startPointer = 0;
while (startPointer < endPointer)
{
//get the char ascii and minus 'a' value - so that we get 0 to 26 alphabets
//ignore case of course.
var valA = Char.ToLower(source[startPointer]) - 'a';
var valB = Char.ToLower(source[endPointer]) - 'a';
if (valA < 0 || valA > 26)
{
startPointer++;
}
else if (valB < 0 || valB > 26)
{
endPointer--;
}
else if (valA != valB)
{
return false;
}
else {
startPointer++;
endPointer--;
}
}
return true;
}
public static bool IsPalindrome(string source, bool alphaNumericOnly = true)
{
if (string.IsNullOrEmpty(source))
{
return false;
}
var endPointer = source.Length-1;
var startPointer = 0;
while (startPointer < endPointer)
{
//get the char ascii and minus 'a' value - so that we get 0 to 26 alphabets
//ignore case of course.
var valA = Char.ToLower(source[startPointer]) - 'a';
var valB = Char.ToLower(source[endPointer]) - 'a';
if (valA < 0 || valA > 26)
{
startPointer++;
}
else if (valB < 0 || valB > 26)
{
endPointer--;
}
else if (valA != valB)
{
return false;
}
else {
startPointer++;
endPointer--;
}
}
return true;
public static bool IsPalindrome(string source, bool alphaNumericOnly = true)
{
if (string.IsNullOrEmpty(source))
{
return false;
}
var endPointer = source.Length-1;
var startPointer = 0;
while (startPointer < endPointer)
{
//get the char ascii and minus 'a' value - so that we get 0 to 26 alphabets
//ignore case of course.
var valA = Char.ToLower(source[startPointer]) - 'a';
var valB = Char.ToLower(source[endPointer]) - 'a';
if (valA < 0 || valA > 26)
{
startPointer++;
}
else if (valB < 0 || valB > 26)
{
endPointer--;
}
else if (valA != valB)
{
return false;
}
else {
startPointer++;
endPointer--;
}
}
return true;
}
public static bool IsPalindrome(string source, bool alphaNumericOnly = true)
{
if (string.IsNullOrEmpty(source))
{
return false;
}
var endPointer = source.Length-1;
var startPointer = 0;
while (startPointer < endPointer)
{
//get the char ascii and minus 'a' value - so that we get 0 to 26 alphabets
//ignore case of course.
var valA = Char.ToLower(source[startPointer]) - 'a';
var valB = Char.ToLower(source[endPointer]) - 'a';
if (valA < 0 || valA > 26)
{
startPointer++;
}
else if (valB < 0 || valB > 26)
{
endPointer--;
}
else if (valA != valB)
{
return false;
}
else {
startPointer++;
endPointer--;
}
}
return true;
}
public static bool IsPalindrome(string source, bool alphaNumericOnly = true)
{
if (string.IsNullOrEmpty(source))
{
return false;
}
var endPointer = source.Length-1;
var startPointer = 0;
while (startPointer < endPointer)
{
//get the char ascii and minus 'a' value - so that we get 0 to 26 alphabets
//ignore case of course.
var valA = Char.ToLower(source[startPointer]) - 'a';
var valB = Char.ToLower(source[endPointer]) - 'a';
if (valA < 0 || valA > 26)
{
startPointer++;
}
else if (valB < 0 || valB > 26)
{
endPointer--;
}
else if (valA != valB)
{
return false;
}
else {
startPointer++;
endPointer--;
}
}
return true;
}
{public static bool IsPalindrome(string source, bool alphaNumericOnly = true)
{
if (string.IsNullOrEmpty(source))
{
return false;
}
var endPointer = source.Length-1;
var startPointer = 0;
while (startPointer < endPointer)
{
//get the char ascii and minus 'a' value - so that we get 0 to 26 alphabets
//ignore case of course.
var valA = Char.ToLower(source[startPointer]) - 'a';
var valB = Char.ToLower(source[endPointer]) - 'a';
if (valA < 0 || valA > 26)
{
startPointer++;
}
else if (valB < 0 || valB > 26)
{
endPointer--;
}
else if (valA != valB)
{
return false;
}
else {
startPointer++;
endPointer--;
}
}
return true;
}
}
public static bool IsPalindrome(string source, bool alphaNumericOnly = true)
{
if (string.IsNullOrEmpty(source))
{
return false;
}
var endPointer = source.Length-1;
var startPointer = 0;
while (startPointer < endPointer)
{
//get the char ascii and minus 'a' value - so that we get 0 to 26 alphabets
//ignore case of course.
var valA = Char.ToLower(source[startPointer]) - 'a';
var valB = Char.ToLower(source[endPointer]) - 'a';
if (valA < 0 || valA > 26)
{
startPointer++;
}
else if (valB < 0 || valB > 26)
{
endPointer--;
}
else if (valA != valB)
{
return false;
}
else {
startPointer++;
endPointer--;
}
}
return true;
}
public static bool IsPalindrome(string source, bool alphaNumericOnly = true)
{
if (string.IsNullOrEmpty(source))
{
return false;
}
var endPointer = source.Length-1;
var startPointer = 0;
while (startPointer < endPointer)
{
//get the char ascii and minus 'a' value - so that we get 0 to 26 alphabets
//ignore case of course.
var valA = Char.ToLower(source[startPointer]) - 'a';
var valB = Char.ToLower(source[endPointer]) - 'a';
if (valA < 0 || valA > 26)
{
startPointer++;
}
else if (valB < 0 || valB > 26)
{
endPointer--;
}
else if (valA != valB)
{
return false;
}
else {
startPointer++;
endPointer--;
}
}
return true;
}
This would work in C#
public static bool chackIfPalindrom(string s)
{
if (string.IsNullOrEmpty(s) || s.Length < 2)
{
return false;
}
else
{
int startIdex = 0;
int endIndex = s.Length-1;
while (startIdex <= endIndex)
{
while (isSpecialChar(s[startIdex]))
{
startIdex++;
}
while (isSpecialChar(s[endIndex]))
{
endIndex--;
}
if (s[startIdex].ToString().ToLower() != s[endIndex].ToString().ToLower())
{
return false;
}
else
{
startIdex++;
endIndex--;
}
}
return true;
}
}
public static bool isSpecialChar(char s)
{
int val =(int)s;
if (val >= 20 && val <= 47)
{
return true;
}
else
{
return false;
}
}
public static boolean isPaldrome(String str) {
if (str == null || str.length() == 0)
return false;
int i = 0;
int j = str.length() - 1;
while (i < j) {
char left = str.charAt(i);
char right = str.charAt(j);
while (!Character.isAlphabetic(left) && i < str.length()) {
left = str.charAt(++i);
}
while (!Character.isAlphabetic(right) && j >= 0) {
right = str.charAt(--j);
}
if (Character.toLowerCase(right) != Character.toLowerCase(left))
return false;
i++;
j--;
}
return true;
}
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv) {
char* str;
char l;
char r;
int len;
int i;
int j;
int b;
if ( argc != 2 ) {
printf("num args is %d\n", argc);
return 1;
}
str = argv[1];
len = strlen(str);
printf("Str read is %s\n", str);
for (i = 0, j = len, b = 1; b && i < j ; ) {
if ((str[i] >= '0' && str[i] <= '9') || (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
if ((str[j] >= '0' && str[j] <= '9') || (str[j] >= 'a' && str[j] <= 'z') || (str[j] >= 'A' && str[j] <= 'Z')) {
if (str[i] >= 0x41 && str[i] <= 0x5A) {
l = 0x20;
} else {
l = 0x00;
}
if (str[j] >= 0x41 && str[j] <= 0x5A) {
r = 0x20;
} else {
r = 0x00;
}
if ( str[i] + l != str[j] + r) {
printf("breaking here because %c at %d != %c at %d", str[i], i, str[j], j );
b = 0;
}
i ++;
j --;
} else {
j --;
}
} else {
i ++;
}
}
if (b) {
printf("Str %s is a Palindrome\n", str);
}
}
In C, be careful if you use ! on bash, quote your string with single quotes
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv) {
char* str;
char l;
char r;
int len;
int i;
int j;
int b;
if ( argc != 2 ) {
printf("num args is %d\n", argc);
return 1;
}
str = argv[1];
len = strlen(str);
printf("Str read is %s\n", str);
for (i = 0, j = len, b = 1; b && i < j ; ) {
if ((str[i] >= '0' && str[i] <= '9') || (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
if ((str[j] >= '0' && str[j] <= '9') || (str[j] >= 'a' && str[j] <= 'z') || (str[j] >= 'A' && str[j] <= 'Z')) {
if (str[i] >= 0x41 && str[i] <= 0x5A) {
l = 0x20;
} else {
l = 0x00;
}
if (str[j] >= 0x41 && str[j] <= 0x5A) {
r = 0x20;
} else {
r = 0x00;
}
if ( str[i] + l != str[j] + r) {
printf("breaking here because %c at %d != %c at %d", str[i], i, str[j], j );
b = 0;
}
i ++;
j --;
} else {
j --;
}
} else {
i ++;
}
}
if (b) {
printf("Str %s is a Palindrome\n", str);
}
}
public boolean isPalindrome(String strr){
if( strr == null || strr.length() <= 0){
return true;
}
char[] arr = strr.toCharArray();
int i = 0, j = arr.length -1;
while(i < j){
//check for lowercase, uppercase
//check for unwanted characters..
char cI = arr[i];
//alpha numeric characters..
if(!isalphanumericCharacter(cI)){
i++;
continue;
}
char cJ = arr[j];
//alpha numeric characters..
if(!isalphanumericCharacter(cJ)){
j--;
continue;
}
if((cJ == cI) || Math.abs(cI-cJ) == 32){
j--;
i++;
}else{
return false;
}
}
return true;
}
public boolean isalphanumericCharacter(char c){
int value = (int) c;
if((value >= 48 && value <= 57)
|| (value >= 65 && value <= 90)
|| (value >= 97 && value <= 122)
){
return true;
}
return false;
}
#include <iostream>
bool palindrome(const std::string &string) {
int a = -1;
int b = (int)string.size();
while (true) {
do {
++a;
} while(a < b && !isalpha(string[a]));
do {
--b;
} while (a < b && !isalpha(string[b]));
if (a >= b) {
return true;
}
if (toupper(string[a]) != toupper(string[b])) {
return false;
}
}
}
int main(int argc, const char * argv[]) {
std::cout << palindrome("A man, a plan, a canal, Panama!") << std::endl;
}
I used Swift to answer this. I separated the solution into two methods.
1. Sanitise the string.
2. to find out if said string is a palindrome using recursion.
PS:
• We only need to sanitise the string once.
• Using NSString substringWithRange is much easier/cleaner solution
func sanitization(str: String) ->String {
let charactersToRemove = NSCharacterSet.alphanumericCharacterSet().invertedSet
var strippedString = str.componentsSeparatedByCharactersInSet(charactersToRemove)
var cleanString = "".join(strippedString)
return cleanString.lowercaseString
}
func palindrome(str: String) -> Bool {
if (count(str) <= 1) {
return true
}
for aChar in str {
let results = palindrome(str.substringWithRange( Range<String.Index>(start: advance(str.startIndex, 1), end: advance(str.startIndex, count(str) - 1))))
let boundryWords = str[str.startIndex] == str[advance(str.startIndex, count(str) - 1)]
return ( boundryWords && results)
}
return false
}
let test = ""
let test1 = "A car, a man, a maraca."
let test2 = "Are we not drawn onward to new era?"
let test3 = "Not a palindrome, no chance"
let test4 = "A"
let test5 = "Naughty dog"
palindrome(sanitization(test1))
palindrome(sanitization(test2))
palindrome(sanitization(test3))
palindrome(sanitization(test4))
palindrome(sanitization(test5))
Output:
true
true
false
true
false
Objective-C Solution:
- (BOOL)validatePalindrome:(NSString *)stringToEval
{
stringToEval = [self cleanString:stringToEval];
NSUInteger startIndex = 0;
NSUInteger endIndex = stringToEval.length-1;
while (startIndex < endIndex) {
if (![[stringToEval substringWithRange:NSMakeRange(startIndex, 1)] isEqualToString:[stringToEval substringWithRange:NSMakeRange(endIndex, 1)]]) {
return NO;
}
startIndex++;
endIndex--;
}
return YES;
}
- (NSString *)cleanString:(NSString *)stringToClean
{
NSCharacterSet *charactersToRemove = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
NSString *newString = [[stringToClean componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@""];
return newString;
}
javascript version
var sample = "A man, a plan, a canal, Panama!"
console.log(isPal(sample));
function isPal (str){
var i = 0, j = str.length-1;
while(i < j){
if ( isLetter(str[i]) && isLetter(str[j]) && str[i].toLowerCase() != str[j].toLowerCase()){
return false;
}
if ( isLetter(str[i]) && isLetter(str[j]) ) {
i++;
j--;
}
else{
if (!isLetter(str[i])) i++;
if (!isLetter(str[j])) j--
}
console.log(str[i], str[j], i, j);
}
return true;
}
function isLetter (c){
return (c <= 'Z' && c >= 'A') || (c <= 'z' && c >= 'a');
}
C++ version
#include <iostream>
#include <string>
using namespace std;
inline bool IsValid(char c)
{
return (c >= 'a' && c <= 'z') //lowercase alpha
|| (c >= 'A' && c <= 'Z') //Uppercase alpha
|| (c >= '0' && c <= '9'); //Numerics
}
inline char ToLower(char c)
{
if ( c >= 'A' && c <= 'Z')
return c - 'A' + 'a';
return c;
}
bool IsPalindrome( string str)
{
string::iterator i = str.begin();
string::iterator j = str.end() - 1;
string::iterator beg = str.begin();
string::iterator end = str.end();
do {
while( i != end && !IsValid(*i) ) ++i; // get valid char from current i position
while( !IsValid(*j) ) { --j; if (j == beg) break; } // get valid char from current j position
if ( i > j)
break;
if ( ToLower( *i) != ToLower( *j))
return false;
++i; --j;
} while(1);
return true;
}
One more
#include <iostream>
#include <string>
using namespace std;
inline bool IsValid(char c)
{
return (c >= 'a' && c <= 'z') //lowercase alpha
|| (c >= 'A' && c <= 'Z') //Uppercase alpha
|| (c >= '0' && c <= '9'); //Numerics
}
inline char ToLower(char c)
{
if ( c >= 'A' && c <= 'Z')
return c - 'A' + 'a';
return c;
}
bool IsPalindrome( string str)
{
string::iterator i = str.begin();
string::iterator j = str.end() - 1;
while ( i < j ) {
if ( !IsValid(*i) ) { ++i; continue; }
if ( !IsValid(*j) ) { --j; continue; }
if ( ToLower( *i) != ToLower( *j))
return false;
++i;--j;
}
return true;
}
public boolean checkPalindrome(char[] letters,int length)
{
int i=0;
int j=length-1;
boolean flag=true;
boolean flag2=false;
while( i < j && flag == true )
{
while(!Character.isLetter(letters[i]) && i<length)
i++;
while(!Character.isLetter(letters[j]) && i<length && i < j)
j--;
if(i < j)
{
if(letters[i]==letters[j])
{
i++;
j--;
flag2=true;
}
else
{
flag =false;
}
}
}
return flag&&flag2;
}
Another javascript version:
function isPalindrome(str){
var length = str.length,
left = 0,
right = length - 1,
a = null,
b = null,
aIsLetter = false,
bIsLetter = false,
itReallyIs = true
;
function isLetter(str) {
return /^[a-z0-9]+$/i.test(str);
}
while(left < length && right >= 0){
a = str[left].toLowerCase();
b = str[right].toLowerCase();
aIsLetter = isLetter(a);
bIsLetter = isLetter(b);
if(aIsLetter && bIsLetter){ // both are letters, just compare
if(a !== b){
itReallyIs = false;
break;
}
else{
++left;
--right;
}
}
else{ // only shift if non-alphanumeric
if(!aIsLetter){
++left;
}
if(!bIsLetter){
--right;
}
}
}
return itReallyIs;
}
Another javascript version:
function isPalindrome(str){
var length = str.length,
left = 0,
right = length - 1,
a = null,
b = null,
aIsLetter = false,
bIsLetter = false,
itReallyIs = true
;
function isLetter(str) {
return /^[a-z0-9]+$/i.test(str);
}
while(left < length && right >= 0){
a = str[left].toLowerCase();
b = str[right].toLowerCase();
aIsLetter = isLetter(a);
bIsLetter = isLetter(b);
if(aIsLetter && bIsLetter){ // both are letters, just compare
if(a !== b){
itReallyIs = false;
break;
}
else{
++left;
--right;
}
}
else{ // only shift if non-alphanumeric
if(!aIsLetter){
++left;
}
if(!bIsLetter){
--right;
}
}
}
return itReallyIs;
}
val p = "A man, a plan, a canal, Panama!"
println(isP(p))
def isP(s: String): Boolean = {
var start: Int = 0
var end: Int = s.size - 1
while (start <= end) {
while (s(start).toString matches "[^a-zA-Z0-9]{1}") {
start = start + 1
}
while (s(end).toString matches "[^a-zA-Z0-9]{1}") {
end = end - 1
}
if (s(start).toLower != s(end).toLower) {
return false
}
start = start + 1
end = end - 1
}
true
}
static bool IsPalindromeOnlyChars(string input)
{
int i = 0, j = input.Length - 1;
input = input.ToLower();
while (i < j)
{
while (!(('a' <= input[i] && input[i] <= 'z')))
i++;
while (!(('a' <= input[j] && input[j] <= 'z')))
j--;
if (input[i] != input[j])
return false;
i++;
j--;
}
return true;
}
bool IsChar(char input){
if (input >= ‘a’ && input <= ‘z’)
return true;
else if (input >= ‘A’ && input <= ‘Z’)
return true;
else
return false;
}
bool Palindrome(char * input){
int size = 0;
char *tmp = input;
while(*tmp != ‘\0’){
size++;
tmp++;
}
int front = 0;
int back = size - 1;
while (front < back){
while( !IsChar(input[front])){
front ++;
}
while( !IsChar(input[back])){
back —;
}
if (tolower(input[front]) == tolower( input[back]) ){
front ++;
back —;
}
else
return false;
}
return true;
}
Move two counter from start and end of the string, skip the non chracters.
private static boolean isPalindrom(final String str) {
if (str == null || str.isEmpty())
return false;
String testStr = str.toLowerCase();
int i = 0;
int j = testStr.length() - 1;
// start two counters from start and end moving towards each other
while (i != j) {
// if not valid char, skip
if(!Character.isLetterOrDigit(testStr.charAt(i))) {
i++;
continue;
}
if(!Character.isLetterOrDigit(testStr.charAt(j))) {
j--;
continue;
}
if (testStr.charAt(i) != testStr.charAt(j))
return false;
i++;
j--;
}
return true;
}
// output:
- guilhebl May 05, 2015true
true
false