zoukankan      html  css  js  c++  java
  • 忽略大小写,只关注字母和数字,判断是否是回文

    在我的 Xcode 上明明行为都是正常的,但是 leetcode 总是说测试到 “ab” 的时候,我的程序返回的是 true。我特么再试几次返回的都是 false,所以觉得是不是网站错了。

    首先是我一开始写的版本,简单倒是简单,只是效率低:

    bool isPalindrome(string s) {
        if (s.empty()){
            return true;
        }
        
        string cleanStr;
        for (const auto& ch : s){
            auto&& i = static_cast<int>(ch);
            if (isalpha(i) && isupper(i)){
                cleanStr.push_back(tolower(i));
            }
            else if (isalpha(i) || isdigit(i)){
                cleanStr.push_back(ch);
            }
        }
        return (cleanStr == string(cleanStr.crbegin(), cleanStr.crend()));
    }

    上面的代码通过了,只是下面的代码就出现了上面说到的问题:

    bool isPalindrome(string s) {
        if (s.empty()){
            return true;
        }
        
        auto beginIt = find_if(s.cbegin(), s.cend(), [](auto c){return isalnum(c);});
        if (beginIt == s.cend()){
            return true;
        }
        
        auto endIt = find_if(s.crbegin(), s.crend(), [](auto c){return isalnum(c);});
        
        char* begin = &s[beginIt - s.cbegin()];
        char* end   = &s[s.crend() - endIt - 1];
        
        auto toUniformFormat = [](char*& ch)
        {
            auto&& i = static_cast<int>(*ch);
            return (isupper(i)? static_cast<char>(tolower(i)) : *ch);
        };
        
        while (begin <= end) {
            if (toUniformFormat(begin) != toUniformFormat(end)) {
                return false;
            }
            
            while (!isalnum(*++begin));
            while (!isalnum(*--end));
        }
        return true;
    }
  • 相关阅读:
    05_XML的解析_01_dom4j 解析
    04_SSM框架整合(Spring+SpringMVC+MyBatis)
    03_入门程序(注解方式,掌握)
    02_入门程序(非注解方式,了解)
    01_SpringMVC流程架构图
    21_resultMap和resultType总结
    20_高级映射:多对多查询
    inline函数的总结
    【C++】C++函数重载的总结
    优先队列
  • 原文地址:https://www.cnblogs.com/wuOverflow/p/4721376.html
Copyright © 2011-2022 走看看