6.25->27 validPalid & strStr & atoi

  • to do


Aibohphobia :D

**1】Valid Palindrome **
or better: usetransform (InputIterator first1, InputIterator last1, OutputIterator result, UnaryOperation op) ;
useisalnum() to check

    bool isPalindrome(string s) {
        for (auto i=s.begin(); i!=s.end(); ) {
            *i = tolower(*i);
            if ( ('a'<=*i && *i<='z') || isdigit(*i) ) {
                ++i;
            } else {
               s.erase(i); 
            }
        }
        if (s.empty()) return true;
        for(auto l=s.begin(), r=s.end()-1; l<r; ++l, --r) {
            if (*l != *r) return false;
        }
        return true;
    }

2] Implement strStr()
一遍过啦~

看KMP算法

    int strStr(string haystack, string needle) {
        if (needle.empty()) return 0;
        if ( haystack.empty() || (needle.size() > haystack.size()) ) return -1;
        
        for (int h=0; h<haystack.size(); ++h) {
            auto n = needle.begin();
            if (haystack[h] != *n) continue; 
            
            int lasth=h;
            while (haystack[h] == *n) {
                if ( ++n == needle.end() ) return lasth;
                if ( ++h >= haystack.size() ) return -1;
            }
            h = lasth;
        }
        return -1;
    }

3] String to Integer (atoi)

重写的时候再简化下

        int i=0;
        while (i<str.size() && str[i]==' ') ++i;
        if (i == str.size()) return 0;
        
        bool neg = str[i]=='-'? true : false;
        if (str[i]=='+' || str[i]=='-') ++i;
        
        int ret = 0;
        int warnMax = INT_MAX/10;
        int lastMax = INT_MAX%10;
        int warnMin = INT_MIN/10;
        int lastMin = INT_MIN%10;

        for (; i<str.size(); ++i) {
            if (!isdigit(str[i])) return ret;
            if ( (ret>warnMax) || 
                                ( (ret==warnMax) && (str[i]-'0' >= lastMax) ) ) return INT_MAX;
            if ( (ret<warnMin) ||
                                ( (ret==warnMin) && (str[i]-'0' >= -lastMin) ) ) return INT_MIN;
            ret *= 10;
            ret += neg? -(str[i]-'0') : (str[i]-'0');
        }
        return ret;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容