categories: [Blog,Algorithm]


125. 验证回文串

难度简单
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: “A man, a plan, a canal: Panama”
输出: true

示例 2:
输入: “race a car”
输出: false

  1. class Solution {
  2. public boolean isPalindrome(String s) {
  3. StringBuffer sgood = new StringBuffer();
  4. int length = s.length();
  5. for (int i = 0; i < length; i++) {
  6. char ch = s.charAt(i);
  7. if (Character.isLetterOrDigit(ch)) {
  8. sgood.append(Character.toLowerCase(ch));
  9. }
  10. }
  11. StringBuffer sgood_rev = new StringBuffer(sgood).reverse();
  12. return sgood.toString().equals(sgood_rev.toString());
  13. }
  14. // 作者:LeetCode-Solution
  15. // 链接:https://leetcode-cn.com/problems/valid-palindrome/solution/yan-zheng-hui-wen-chuan-by-leetcode-solution/
  16. }
  1. class Solution {
  2. public boolean isPalindrome(String s) {
  3. StringBuffer sgood = new StringBuffer();
  4. int length = s.length();
  5. for (int i = 0; i < length; i++) {
  6. char ch = s.charAt(i);
  7. if (Character.isLetterOrDigit(ch)) {
  8. sgood.append(Character.toLowerCase(ch));
  9. }
  10. }
  11. int n = sgood.length();
  12. int left = 0, right = n - 1;
  13. while (left < right) {
  14. if (Character.toLowerCase(sgood.charAt(left)) != Character.toLowerCase(sgood.charAt(right))) {
  15. return false;
  16. }
  17. ++left;
  18. --right;
  19. }
  20. return true;
  21. }
  22. // 作者:LeetCode-Solution
  23. // 链接:https://leetcode-cn.com/problems/valid-palindrome/solution/yan-zheng-hui-wen-chuan-by-leetcode-solution/
  24. }
  1. class Solution {
  2. public boolean isPalindrome(String s) {
  3. int n = s.length();
  4. int left = 0, right = n - 1;
  5. while (left < right) {
  6. while (left < right &&
  7. !Character.isLetterOrDigit(s.charAt(left))) {
  8. ++left;
  9. }
  10. while (left < right &&
  11. !Character.isLetterOrDigit(s.charAt(right))) {
  12. --right;
  13. }
  14. if (left < right) {
  15. if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
  16. return false;
  17. }
  18. ++left;
  19. --right;
  20. } //这个left < right去掉貌似可以,while里三处必须有.
  21. }
  22. return true;
  23. }
  24. // 作者:LeetCode-Solution
  25. // 链接:https://leetcode-cn.com/problems/valid-palindrome/solution/yan-zheng-hui-wen-chuan-by-leetcode-solution/
  26. }