zoukankan      html  css  js  c++  java
  • [LeetCode]125. Valid Palindrome

    题目描述:

    Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

    For example,
    "A man, a plan, a canal: Panama" is a palindrome.
    "race a car" is not a palindrome.

    Note:
    Have you consider that the string might be empty? This is a good question to ask during an interview.

    For the purpose of this problem, we define empty string as valid palindrome.

    思路:

    判断是否回文字符串。非字符、非数字不算,大小写不分。
    首先去除非数字、非字符的标点等,存入另一个字符串(不需要存入另外的字符串,只要从头和尾开始比较就行了,遇到非字母跳过,相等则继续,直到i = j)
    然后从头和尾开始比较,直到中间位置为止。如果都相等则返回true
    i 和 j 表示字符串的开头和结尾位,如果不是合法的字符则i++,j--,如果合法则将它转化为小写字符,再比较,相等则比较下一位,否则退出。
    最终返回true
    注意while的用法,continue的用法
    大小写均转化为小写是character.toLowerCase();

     1 public class Solution125 {
     2     public boolean isPalindrome(String s) {
     3         if(s == null) return false;
     4         int i=0;
     5         int j = s.length()-1;
     6         while(i<j){
     7                 if(!isAlphanumeric(s.charAt(i)))  {i++;continue;}
     8                 if(!isAlphanumeric(s.charAt(j)))  {j--;continue;}
     9                 if(Character.toLowerCase(s.charAt(i))!=Character.toLowerCase(s.charAt(j))) {
    10                     return false;
    11                 }else {
    12                     i++;
    13                     j--;
    14                 }
    15             }
    16         return true;
    17         }
    18         
    19     public boolean isAlphanumeric(char c){
    20         if((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))
    21             {return true;}
    22         return false;
    23     }
    24     public static void main(String[] args) {
    25         // TODO Auto-generated method stub
    26         Solution125 solution125 = new Solution125();
    27         String s = "A man, a plan, a canal: Panama";
    28         if(solution125.isPalindrome(s)==true)
    29             System.out.println("1");
    30         else {
    31             System.out.println("0");
    32         }
    33     }
    34 
    35 }
  • 相关阅读:
    php
    php数据排序---array_multisort
    IOS 线程描述
    IOS 进程描述
    IOS 强指针(strong)和弱指针(weak)
    IOS autosizing(设置控件的固定位置大小)
    IOS UIActivityIndicatorView动画
    IOS UIImageView的帧动画
    IOS Block动画
    IOS UIView动画(封装动画)
  • 原文地址:https://www.cnblogs.com/zlz099/p/8184734.html
Copyright © 2011-2022 走看看