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;   
        }
    }
  • 相关阅读:
    推销员问题
    string类实现
    链表倒数第k个节点
    设计模式之单例模式大全
    空类 sizeof 为什么是1
    类的三种继承方式
    单例模式典型创建方法(三种)
    虚函数实现
    链表删除结点
    TCP的状态转移
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4862130.html
Copyright © 2011-2022 走看看