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.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
public class Solution { public boolean isPalindrome(String s) { // Start typing your Java solution below // DO NOT write main() function if(s.length() == 1||s.isEmpty()) return true; s= s.replaceAll("\\W+",""); // // It means replace all non-word character with ""(nothing). // \\W means non- word; while \\w means word. // (Thinking in Java talked about this concept). s = s.toLowerCase(); int i = 0, j = s.length() -1 ; while(i<=j){ if(s.charAt(i) != s.charAt(j)){ return false; } i++; j--; } return true; } }
public class Solution { public boolean isPalindrome(String s) { // Start typing your Java solution below // DO NOT write main() function if(s.length() == 0 ||s.length() == 1 ) return true; s = s.replaceAll("\\W+",""); s = s.toLowerCase(); for(int i = 0 ; i < s.length()/2 ; i++){ if(s.charAt(i)!= s.charAt(s.length()-1-i)){ return false; } } return true; } }
mistake: make any changes to string, let s = s.somefunction not only do s.something!