• 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);
        }
    }
    View Code

    他人代码:

    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);
        }
    }
    View Code

    学习之处:

    • Character.isLetter(c) Character.isDigit(c) Character.toLowerCase(c)  Character还有这几个API不错
    • 写代码的时候,尽量的简洁和功能划分,比如我的代码里面的isAlpha和isEqual都可以用一行代码解决,这样就不要用多行,注意功能划分。 
  • 相关阅读:
    一本通1273货币系统(方案数背包)
    背包体积循环正序和逆序的区别
    Python字典的底层原理和优缺点
    Linux各目录及每个目录的详细介绍
    openwrt 下python程序后台运行,并将打印信息保存文件
    pycharm同一目录下无法import其他文件
    python sqlite3学习笔记
    python sqlite3查询表记录
    Pycharm快捷键的使用
    Python3 Address already in use 解决方法
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4337446.html
Copyright © 2020-2023  润新知