题目链接:125. 验证回文串 - 力扣(LeetCode)
主要是将大写字母转换成小写(将字母异或32即可转换大小),并将数字也存入数组,除去其他字符。反转是通过list反相输入再比较实现的。
public static boolean isPalindrome(String s){boolean ans=true;List<Character>list=new ArrayList<>();for (int i=0;i<s.length();i++){char x=s.charAt(i);if (x>=97&&x<=122||x>=48&&x<=57)list.add(x);if (x>=65&&x<=90)list.add((char) (x^32));}List<Character>list1=new ArrayList<>();for (int i=list.size()-1;i>=0;i--){list1.add(list.get(i));}
// 验证字符串的内容
// for (Character x:list)
// System.out.print(x);
// System.out.println();
// for (Character x:list1)
// System.out.print(x);
// System.out.println();for (int i=0;i<list.size();i++){if(list.get(i)!=list1.get(i)) {ans = false;return ans;}}return ans;}
测试用例:
String s="A man, a plan, a canal: Panama";
运行结果:
trueProcess finished with exit code 0
两个字符串的内容:
amanaplanacanalpanama
amanaplanacanalpanama
trueProcess finished with exit code 0