Valid Palindrome
Valid Palindrome
问题:
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
思路:
简单的数学推导
我的代码:
public class Solution { public boolean isPalindrome(String s) { if(s == null || s.length() == 0) return true; int left = 0; int right = s.length() - 1; while(left < right) { while(!isAlpha(s.charAt(left)) && left < right) left++; while(!isAlpha(s.charAt(right)) && left < right) right--; if(!isEqual(s.charAt(left), s.charAt(right))) return false; left ++; right --; } return true; } public boolean isAlpha(char c) { return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')); } public boolean isEqual(char left, char right) { return (left == right || Math.abs(left-right) == 32); } }
他人代码:
public class Solution { public boolean isPalindrome(String s) { if (s == null || s.length() == 0) { return true; } int front = 0; int end = s.length() - 1; while (front < end) { while (front < s.length() && !isvalid(s.charAt(front))){ // nead to check range of a/b front++; } if (front == s.length()) { // for emtpy string “.,,,” return true; } while (end >= 0 && ! isvalid(s.charAt(end))) { // same here, need to check border of a,b end--; } if (Character.toLowerCase(s.charAt(front)) != Character.toLowerCase(s.charAt(end))) { break; } else { front++; end--; } } return end <= front; } private boolean isvalid (char c) { return Character.isLetter(c) || Character.isDigit(c); } }
学习之处:
- Character.isLetter(c) Character.isDigit(c) Character.toLowerCase(c) Character还有这几个API不错
- 写代码的时候,尽量的简洁和功能划分,比如我的代码里面的isAlpha和isEqual都可以用一行代码解决,这样就不要用多行,注意功能划分。
posted on 2015-03-14 13:53 zhouzhou0615 阅读(124) 评论(0) 编辑 收藏 举报