zoukankan      html  css  js  c++  java
  • LeetCode OJ:Valid Palindrome(验证回文)

    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.

    验证回文与否,这个估计大家学c语言的时候就都写过:

     1 class Solution {
     2 public:
     3     bool isPalindrome(string s) {
     4         int len = s.length();
     5         for(int i = 0, j = len - 1; i < j ;++i, --j){
     6             while(i < j && (!isalpha(s[i]) && !isdigit(s[i])))
     7                 i++;
     8             while(j > i && (!isalpha(s[j]) && !isdigit(s[j])))
     9                 j--;
    10             if(isalpha(s[i]) && isalpha(s[j])){
    11                 if(toupper(s[i]) == toupper(s[j]))
    12                     continue;
    13                 else return false;
    14             }else{
    15                 if(s[i] == s[j])
    16                     continue;
    17                 return false;
    18             }
    19         }
    20         return true;
    21     }
    22 };

     java版本的代码如下所示,算法没有变化:

    public class Solution {
        public boolean isPalindrome(String s) {
             int sz = s.length();
             int beg = 0, end = sz - 1;
             while(beg < end){
                 while(!Character.isLetter(s.charAt(beg)) && !Character.isDigit(s.charAt(beg))){
                     if(beg < end) beg++;
                     else return true;
                 }
                 while(!Character.isLetter(s.charAt(end)) && !Character.isDigit(s.charAt(end))){
                     if(beg < end) end--;
                     else return true;
                 }
                 if(Character.toUpperCase(s.charAt(beg)) == Character.toUpperCase(s.charAt(end))){
                     beg++;
                     end--;
                 }else{
                     return false;
                 }
             }
             return true;   
        }
    }
  • 相关阅读:
    js数组中indesOf方法的使用
    js之数组排序
    大神的博客地址liferay
    CRM项目总结-封装PortletURLUtil
    有待整理
    摘要JSR168 PORLET标准手册汉化整理
    蓝色表格 -- 材料
    node 项目材料 集合
    一个浮动 css3效果
    代码 工具
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4862130.html
Copyright © 2011-2022 走看看