把相同的词汇或句子,调换位置或颠倒过来,产生首尾回环叫做回文。
如“abba”、“abccba”、12321、123321是“回文”,“abcde”和“ababab”则不是“回文”。
以下核心代码help(s)的效率为O(m)
public class Palindrome {
public static void main(String[] args) {
String s = "A man, a plan, a canal: Panama";
boolean b = isPalindrome(s);
System.out.println(b);
}
public static String tool(String s ){
s = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
return s;
}
public static boolean isPalindrome(String s){
s = tool(s);
return help(s);
}
private static boolean help(String s){
int len = s.length();
int index = 0;
int m = len / 2;
Stack<Character> stack = new Stack<Character>();
while(index < m){
stack.push(s.charAt(index));
index++;
}
if(len % 2 == 1){
index++;
}
while(index < len){
if(stack.empty()){
return false;
}
char a = stack.pop();
if(a != s.charAt(index)){
return false;
}else{
index++;
}
}
return true;
}
}