zoukankan      html  css  js  c++  java
  • LeetCode OJ

    这道题挺简单的,但是需要细心。

    最好的方法是先对string做预处理,然后再判断是否是回文。

    下面是AC代码:

     1 /**
     2      * Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
     3      * @param s
     4      * @return
     5      */
     6     public boolean isPalindrome(String s){
     7         String pre = preProcess(s);
     8         char[] sw = pre.toCharArray();
     9         if(pre==null || pre.length()<=1 )
    10             return true;
    11         int i=0;
    12         int j=pre.length()-1;
    13         while(i<=j){
    14             if(sw[i]!=sw[j])
    15                 return false;
    16             i++;
    17             j--;
    18         }
    19         return true;
    20     }
    21     /**
    22      * pre-processing the string, remove all non-isAlphanumeric
    23      * and change all to lower
    24      * @param s
    25      * @return
    26      */
    27     private String preProcess(String s){
    28         
    29         StringBuffer sb = new StringBuffer();
    30         for(int i=0;i<s.length();i++)
    31             if(isAlphanumeric(s.charAt(i)))
    32                 sb.append(s.charAt(i));
    33         return sb.toString().toLowerCase();
    34     }
    35     /**
    36      * make decision if a character is a alphanumeric
    37      * @param c
    38      * @return
    39      */
    40     private boolean isAlphanumeric(char c){
    41         if(c>='a' && c<='z' || c>='A' && c<='Z' || c>='0'&& c<='9')
    42             return true;
    43         return false;
    44     }
    有问题可以和我联系,bettyting2010#163 dot com
  • 相关阅读:
    DS博客作业06--图
    DS博客作业05--树
    DS博客作业03--栈和队列
    DS博客作业02-线性表
    DS博客作业01--日期抽象数据类型设计与实现
    C语言博客作业06---结构体&文件
    C语言博客作业05---指针
    C语言博客作业04--数组
    DS博客作业08--课程总结
    DS博客作业07--查找
  • 原文地址:https://www.cnblogs.com/echoht/p/3701100.html
Copyright © 2011-2022 走看看