Interview Question
Country: United States
public class Palindrome {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str1="1sunilinus";
if (str1.matches(".*[^a-zA-Z].*$") == true ){
System.out.println("Not a valid string");
return;
}
System.out.println("Is it Palindrome : "+isPalindrome(str1));
}
public static boolean isPalindrome(String s){
char[] str = s.toCharArray();
int len=str.length;
System.out.println("Length of String: "+len);
//loop
int start = 0;
int end = len-1;
while(start<end)
{
if(str[start++] != str[end--])
return(false);
}
return(true);
}
}
Solution in C# (Case and analphabetic charachters are ignored)
public static bool WordCheck(string word)
{
word = word.ToLower();
string reversedWord = string.Empty;
for (int i = word.Length - 1; i >= 0; i--)
{
if (Convert.ToInt32(word[i]) > 96 && Convert.ToInt32(word[i]) < 123)
reversedWord += word[i];
}
return reversedWord == word ? true : false;
}
Solution in JavaScript:
var palindromeCheck = function(string) {
var len = string.length - 1;
var alpha = /^[a-zA-Z]+$/;
for ( var i = 0, k = len; i < k; i++, k-- ) {
while ( !alpha.test(string[i]) ) { i++; }
while ( !alpha.test(string[k]) ) { k--; }
if ( string[i] !== string[k] ) { return false; }
}
return true;
};
Your final solution looks good to me. You could place some of the work with built in functions
My solution in C++ (you can replace isalpha with Character.isLetter(char) and tolower with Character.toLowerCase(char) in java if you like))
- Anonymous August 11, 2014