zoukankan      html  css  js  c++  java
  • isPalindrome

    125. 验证回文串
    给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
    
    说明:本题中,我们将空字符串定义为有效的回文串。
    
    示例 1:
    
    输入: "A man, a plan, a canal: Panama"
    输出: true
    示例 2:
    
    输入: "race a car"
    输出: false
    
    // 双指针
    class Solution {
        public boolean isPalindrome(String s) {
            int head = 0;
            int tail = s.length() - 1;
            while(head < tail){
                while(!Character.isLetterOrDigit(s.charAt(head)) && head < tail){
                    head++;
                }
                while(!Character.isLetterOrDigit(s.charAt(tail)) && head < tail){
                    tail--;
                }
                if(Character.toLowerCase(s.charAt(head)) != Character.toLowerCase(s.charAt(tail))){
                    return false;
                }
                head++;
                tail--;
            }
            return true;
        }
    }
    
    // 自己写的解法..存了一遍,效率很低,推荐用双指针
    class Solution {
        public boolean isPalindrome(String s) {
            List<Character> list = new ArrayList<>();
            for(char c : s.toCharArray()){
                if (Character.isLetter(c))
                    list.add(Character.toLowerCase(c));
                if (Character.isDigit(c)){
                    list.add(c);
                }
            }
            int len = list.size();
            if(len == 0) return true;
            int i = 0;
            for(i = 0; i<=len/2; i++){
                if(list.get(i) != list.get(len-1-i)){
                    break;
                }
            }
    
            return i -1 == len / 2;
        }
    }
    
  • 相关阅读:
    experiment 2
    experiment 5
    php 代码审计之变量覆盖
    experiment 4
    experiment 3
    experiment 1
    2018铁三测评WP
    Lesson 1
    实验四、决策树算法及应用
    实验三 朴素贝叶斯算法及应用
  • 原文地址:https://www.cnblogs.com/athony/p/13059679.html
Copyright © 2011-2022 走看看