This question is quite easy I believe. First step I take is to pre-process the string, eliminate characters except alphanumerical ones. Method prc is responsible for this work.
public class Solution {
public boolean isPalindrome(String s) {
if(s == null) return true;
String lowCase = s.toLowerCase();
String prcdS = prc(lowCase);
if(prcdS.length() < 2) return true;
int i = 0;
int j = prcdS.length() - 1;
while(i<j){// check whether the processed string is palindrome
if(prcdS.charAt(i) != prcdS.charAt(j)) return false;
i++;
j--;
}
return true;
}
public String prc(String s){
StringBuffer result = new StringBuffer();
for(int i = 0; i < s.length(); i ++){
if((s.charAt(i) >= 'a' && s.charAt(i) <= 'z')||(s.charAt(i) >= '0' && s.charAt(i) <= '9')) result.append(s.charAt(i));
}
return result.toString();
}
}
Hello, welcome to Yizhe's Blog. I am Yizhe Liu, graduated from University of Arizona, with Master degree, major in Electrical and Computer Engineering. Actually, I am software guy. In my blog, many posts are about the Leetcode questions. I will post my ideas and implementations, which are accepted by Leetcode. If you have different opinions, please leave comment. I am happy to discuss with you. So lets start rocking them!!!
No comments:
Post a Comment