• 忽略大小写,只关注字母和数字,判断是否是回文


    在我的 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;
    }
  • 相关阅读:
    POJ_2513Colored Sticks 字典树+
    hdu1098:Ignatius's puzzle
    hdu1010:Tempter of the Bone 搜索+剪枝
    轻院1875: 蛤玮的财宝
    POJ3069:Saruman's Army
    轻院1874: 蛤玮学计网
    Educational Codeforces Round 18 E. Colored Balls
    浏览器f12的方法下载资源
    把手机上的新浪微博客户端卸载了
    Xmind使用总结
  • 原文地址:https://www.cnblogs.com/wuOverflow/p/4721376.html
Copyright © 2020-2023  润新知