125.验证回文串
代码
/** (11ms)
*算法一:栈
*/
public boolean isPalindrome(String s) {
if(s == null || s.length() == 0) return true;
Stack<Character> stack = new Stack<>();
List<Character> list = new ArrayList<>();
for (int i = 0; i < s.length(); i++) {
if ((s.charAt(i) >= 'A' && s.charAt(i) <= 'Z') ||(s.charAt(i) >= 'a' && s.charAt(i) <= 'z')){
stack.push((char) (s.charAt(i) | ' '));
list.add((char) (s.charAt(i) | ' '));
}else if (s.charAt(i) >= '0' && s.charAt(i) <= '9'){
stack.push(s.charAt(i));
list.add(s.charAt(i));
}
}
int index = 0;
while (!stack.isEmpty()){
if (stack.pop() != list.get(index++))
return false;
}
return true;
}
/**
* 算法二:双指针
*/
public boolean isPalindrome(String s){
if (s == null || s.length() == 0) return true;
int front = 0,rear = s.length()-1;
while (front <= rear){
while (front < rear && !Character.isAlphabetic(s.charAt(front)) && !Character.isDigit(s.charAt(front)))
front++;
while ( front < rear && !Character.isAlphabetic(s.charAt(rear)) && !Character.isDigit(s.charAt(rear)))
rear--;
if (!s.substring(front,front+1).equalsIgnoreCase(s.substring(rear,rear+1)))
return false;
front++;
rear--;
}
return true;
}