Created
January 26, 2013 08:40
-
-
Save daifu/4641096 to your computer and use it in GitHub Desktop.
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
This file contains hidden or 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
| public class Solution { | |
| public boolean isPalindrome(String s) { | |
| // Start typing your Java solution below | |
| // DO NOT write main() function | |
| int size = s.length(); | |
| String lcs = s.toLowerCase(); | |
| int left = 0; | |
| int right = size - 1; | |
| while(right >= left) { | |
| if(lcs.charAt(right) == lcs.charAt(left)) { | |
| right--; | |
| left++; | |
| } else if(!Character.isLetter(lcs.charAt(right))) { | |
| right--; | |
| } else if(!Character.isLetter(lcs.charAt(left))) { | |
| left++; | |
| } else { | |
| return false; | |
| } | |
| } | |
| return true; | |
| } | |
| } |
public int isPalindrome(String A) {
int size = A.length();
String lcs = A.toLowerCase();
int left = 0;
int right = size - 1;
while(right >= left) {
boolean isDigitComp = (Character.isDigit(lcs.charAt(right)) && Character.isDigit(lcs.charAt(left)))
&& (Integer.parseInt(String.valueOf(lcs.charAt(right))) == Integer.parseInt(String.valueOf(lcs.charAt(left))));
if(isDigitComp || lcs.charAt(right) == lcs.charAt(left)) {
right--;
left++;
} else if(!Character.isDigit(lcs.charAt(right)) && !Character.isLetter(lcs.charAt(right))) {
right--;
} else if(!Character.isDigit(lcs.charAt(left)) && !Character.isLetter(lcs.charAt(left))) {
left++;
} else {
return 0;
}
}
return 1;
}
import re
class Palindrome:
# @param A : string
# @return an integer
def isPalindrome(self, A):
if A == "":
return 1
A = re.sub('[^a-zA-Z0-9]', '', A)
if A == "":
return 1
A = A.lower()
i = 0
j = len(A) - 1
while i < j:
if A[i] != A[j]:
return 0
i += 1
j -= 1
return 1
public static int isPalindrome(String A) {
if(A == null )
{
return 0;
}
A = removeSplChar(A);
System.out.println("After remove char: "+A);
if( A.length() == 0 || A.length() == 1)
{
return 1;
}
boolean ispalindrome = true;
A=A.toLowerCase();
for(int i = 0,j=A.length()-1 ; i<A.length() ; i++,j--)
{
if(A.charAt(i) != A.charAt(j))
{
ispalindrome = false;
break;
}
}
if(ispalindrome)
{
return 1;
}
return 0;
}
private static String removeSplChar(String A) {
String x = "";
for(int i = 0 ; i<A.length() ; i++)
{
int a = A.charAt(i);
if(a>= 65 && a<= 90)
{
x = x+A.charAt(i);
}
if(a>= 97 && a<= 122)
{
x = x+A.charAt(i);
}
if(a>= 48 && a<= 57)
{
x = x+A.charAt(i);
}
}
return x;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This case will fails for numbers