OJ-Problems-Source/LeetCode/刷题.md

51 KiB
Raw Blame History

create by jzf@2018/06/20

[TOC]

作业

627. 交换工资 @2018/06/20

jzf :517ms

update salary 
    set sex = case when sex ='m' then 'f' else 'm' end;

kiritow:563ms

    update salary set sex = case sex
    when 'f' then 'm'
    when 'm' then 'f'
    end

3. 无重复字符的最长子串 @2018/06/20

北河

* 第一版 :392ms
```c++
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        map<char, short> v;
        int max_num = 0;
        for (int i = 0; i < s.size(); ++i) {
            if (v.find(s[i]) != v.end()) {
                if (max_num < v.size()) {
                    max_num = v.size();
                }
                i = v.find(s[i])->second + 1;
                v.clear();
            }
            if (i >= s.size()) {
                break;
            }
            v[s[i]] = i;
            if (max_num < v.size()) {
                max_num = v.size();
            }
        }
        return max_num;
    }
};

```
* 第2版 :32ms
```c++
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        map<char, short> v;
        int max_num = 0;
        for (int i = 0; i < s.size(); ++i) {
            if (v.find(s[i]) != v.end()) {
                if (max_num < v.size()) {
                    max_num = v.size();
                }
                ++i;
                while (i < s.size()) {
                    if (v.find(s[i]) != v.end()) {
                        ++i;
                        continue;
                    }
                    --i;
                    break;
                }
                if (i >= s.size()) {
                    return max_num;
                }
                i = v.find(s[i])->second + 1;
                v.clear();
            }
            if (i >= s.size()) {
                break;
            }
            v[s[i]] = i;
            if (max_num < v.size()) {
                max_num = v.size();
            }
        }
        return max_num;
    }
};
```

jzf :252 ms 8

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int num =1;
        int max =0;
        if(s.length()==1)
        {
            return 1;
        }
        for(size_t i =0;i<s.length();i++)
        {
            
            for(size_t j=i+1;j<s.length();j++)
            {
                int flag =0;
                for(size_t k =i;k<j;k++)
                {
                    if(s[j]==s[k])   
                    {
                        flag =1;
                        break;
                    }
                    num++;
                }
                    if(num>max)
                    {
                        max =num;
                    }
                if(flag ==1)
                {
                    break;
                }
                num =1;
            }
             num =1;
        }
        return max;
    }
};

puck :544ms 2

#ifndef SOLUTION_H
#define SOLUTION_H

#include <algorithm>
#include <string>
#include <set>
using std::string;
class Solution
{
  public:
    int lengthOfLongestSubstring(string s)
    {
        int result{};
        for (std::size_t i{}; i < s.size(); ++i)
        {
            string tmp_str = s.substr(i);
            int cu_length{};
            std::set<char> set_except;
            
            for (auto ch : tmp_str)
            {
                if (set_except.end() == set_except.find(ch))
                {
                    set_except.insert(ch);
                    ++cu_length;
                }
                else
                {
                    break;
                }
            }

            result = std::max(result, cu_length);
        }

        return result;
    }
};

#endif

kiritow 24ms 2

#include <cstdlib>
#include <cstring>
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int sz = s.size();
        int bin[256];
        int maxlen = 0;
        int clen = 0;
        int L = 0;
        while (L < sz)
        {
            memset(bin, 0, sizeof(int) * 256);
            int i;
            for (i = L; i < sz; i++)
            {
                if (bin[s[i]])
                {
                    maxlen = clen > maxlen ? clen : maxlen;
                    clen = 0;
                    L++;
                    break;
                }
                else
                {
                    bin[s[i]] = 1;
                    clen++;
                }
            }
            if (i == sz)
            {
                maxlen = clen > maxlen ? clen : maxlen;
                break;
            }
        }
        return maxlen;
    }
};

知识点

桶排序
sync_with_stdio

总结

1, 对比代码发现,利用现有的数据结构,可以快速出活,而且代码简洁,逻辑清晰。

2, STL不好好用很慢。

494. 目标和 @2018/06/21

jzf

* 第一版 超时  复杂度 n*2^n
```c++
class Solution {
public:  int findTargetSumWays(vector<int>& nums, int S) {
    int n = 0;
    int sum = 0;
    int b = 0;
    int size =nums.size();
    for (size_t k = 0; k <size ; k++)
    {
        b = ((1 << k) | b);
    }
    for (size_t i = 0; i <= b; i++)
    {
        n = 0;
        for (size_t j = 0; j < size; j++)
        {
            n += ((1 << j)&i) ? -nums[j] : nums[j];
        }
        if (n == S)
        {
            sum++;
        }
    }
    return sum;
    }
};
```
* 第二版 

kiritow 24ms 2

class Solution {
public:
    int findTargetSumWays(vector<int>& nums, int S) {
        if (S < -1000 || S>1000) return 0;

        int sz = nums.size();
        int msz = sizeof(int) * 2048;
        int _bin[2048] = { 0 };
        int _xbin[2048] = { 0 };
        int* p = _bin;
        int* q = _xbin;
        memset(p, 0, msz);
        p[1000] = 1;
        
        for (int i = 0; i < sz; i++)
        {
            memset(q, 0, msz);
            for (int j = 0; j < 2048; j++)
            {
                if (p[j])
                {
                    //printf("p[%d]=%d\n", p[j]);
                    // now=j-1000;
                    int L = j - nums[i]; // now-nums[i]+1000
                    int R = j + nums[i];
                    q[L] += p[j];
                    q[R] += p[j];
                    //printf("q[%d]=%d\n", L, q[L]);
                    //printf("q[%d]=%d\n", R, q[R]);
                }
            }
            std::swap(p, q);
        }
        return p[S + 1000];
    }
};

知识点

dfs

bfs

剪枝

记忆搜索

去掉重复

没写dp身败名裂--惠惠语录

601. 体育馆的人流量@2018/06/21

jzf :521ms 抄

    select s1.* 
    from stadium  as s1, stadium  as s2,stadium  as s3 
    where (((s2.id =s1.id+1) and (s3.id =s1.id+2))
           or((s2.id =s1.id-1) and (s3.id =s1.id+1))
           or((s2.id =s1.id-2) and (s3.id =s1.id-1)))
        and 
         (s1.people>=100 and s2.people>=100 and s3.people >=100)
    group by s1.id

知识点

mysql必知必会 16章 自连接

总结

1看了下最快的sql语句感叹逻辑差不过的东西差距真大呀

9. 回文数@2018/06/22

羽柔子 372ms

var isPalindrome = function(x) {
    return x.toString()===x.toString().split("").reverse().join("");
};
  • 第二版 128ms
class Solution {
    int list[10],len=0,i=0;
public:
    bool isPalindrome(int x) {
        if(x<0)return false;
        len=i=0;
        //分解
        while(true){
            if(x>=10){
                list[len++]=x%10;
                x/=10;
            }
            else{
                list[len++]=x;
                break;
            }
        }

        //判断
        --len;
        for(i=0;i<len&&list[i]==list[len];i++,len--);
        return i>=len;
    }
};

jzf

  • 第一版 232ms
    class Solution {
    public:
        bool isPalindrome(int x) {
            int mod;
            int sh =x;
            vector<int> vec;
            if(x <0)
            {
                return false;
            }
            if(x ==0)
            {
                return true;
            }
    
            for(size_t i =0;sh>0;i++)
            {
                vec.push_back(sh%10);
                sh = sh/10;
            }
            vector<int>::iterator i=vec.begin();
            vector<int>::iterator j=vec.end()-1;
            for(;i<j;i++,j--)
            {
                if(*i!=*j)
                {
                    return false;
                }
            }
            return true;  
        }
    };
    
  • 第2版 140ms
    class Solution {
    public: bool isPalindrome(int x) {
           int mod;
           int sh =x;
           vector<int> vec;
           if(x <0)
           {
               return false;
           }
           if(x ==0)
           {
               return true;
           }
           if(x%10 ==0)
           {
               return false;
           }
           for(size_t i =0;sh>0;i++)
           {
               vec.push_back(sh%10);
               sh = sh/10;
           }
           vector<int>::iterator i=vec.begin();
           vector<int>::iterator j=vec.end()-1;
           for(;i<j;i++,j--)
           {
               if(*i!=*j)
               {
                   return false;
               }
           }
           return true;  
       }
    };
    

北河 244ms

  • 第一版
class Solution {
public:
    bool isPalindrome(int x) {
        char p[10], q[10];
        short size = sprintf(p, "%d", x);
        reverse_copy(p, p + size, q);
        return x < 0 ? false : (mismatch(p, p + size / 2 + 1, q).first == (p + size / 2 + 1) ? true : false);               
    }
};
  • 第二版
class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) {
            return false;
        }
        string s = to_string(x);
        return mismatch(s.begin(), s.end(), s.rbegin()).first == s.end();
    }
};

kiritow 120ms

#include <cstdio>
class Solution {
public:
    bool isPalindrome(int x) {
        /*
        // Converting to string is too slow!!
        char buff[64] = { 0 };
        sprintf(buff, "%d", x);
        int len = strlen(buff);
        int L = 0, R = len - 1;
        while (L < R)
        {
            if (buff[L] != buff[R]) return false;
            ++L;
            --R;
        }
        return true;
        */
        if (x < 0) return false;
        int buff[64] = { 0 };
        int c = 0;
        int tx = x;
        while (tx > 0)
        {
            buff[c++] = tx % 10;
            tx /= 10;
        }
        int L = 0, R = c - 1;
        while (L < R)
        {
            if (buff[L] != buff[R]) return false;
            ++L;
            --R;
        }
        return true;
    }
};

puck

#include <string>

class Solution
{
  public:
    bool isPalindrome(int x)
    {
        if (x < 0)
            return false;

        std::string tmp = std::to_string(x);

        std::size_t bi_size = tmp.size() / 2;
        auto half = tmp.begin() + bi_size;
        auto iter = tmp.begin();
        auto riter = tmp.rbegin();
        for (; iter != half; ++iter, ++riter)
        {
            if (*iter != *riter)
                return false;
        }
        return true;
    }
};

总结

1 我在想一个问题 羽柔子撤回了一条消息 喵在想一个问题 --羽柔子语录

225. 用队列实现栈@2018/06/22

羽柔子 0ms

class MyStack {
    int stack[10],index=0;
    
public:
    /** Initialize your data structure here. */
    MyStack() {
    }
    
    /** Push element x onto stack. */
    void push(int x) {
        stack[index++]=x;
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        return stack[--index];
    }
    
    /** Get the top element. */
    int top() {
        return stack[index-1];
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return !index;
    }
};

kiritow

#include <list>
class MyStack {
public:
    /** Initialize your data structure here. */
    MyStack() {
        
    }

    /** Push element x onto stack. */
    void push(int x) {
        lst.push_back(x);
    }

    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int t = lst.back();
        lst.pop_back();
        return t;
    }

    /** Get the top element. */
    int top() {
        return lst.back();
    }

    /** Returns whether the stack is empty. */
    bool empty() {
        return lst.empty();
    }
private:
    std::list<int> lst;
};

28. 实现strStr() @2018/06/23

jzf

  • 第一版 4ms
class Solution {
public:
    int strStr(string haystack, string needle) {
        string::iterator ihay;
        string::iterator inee;
        int ni =haystack.size();
        int nn =needle.size();
        int ret = -1;
        
        if(nn==0)
        {
            return 0;
        }
        if(ni<nn)
        {
            return -1;
        }
        for(size_t i=0;i<ni-nn+1;i++)
        {
            if(!(haystack.substr(i,nn)).compare(needle))
            {
                ret =i;
                break;
            }
        }
        
        return ret;
    }
};

羽柔子

class Solution {
public:
    int strStr(string haystack, string needle) {
        if(needle.size()==0)return 0;
        if(haystack.size()<needle.size())return -1;
        size_t 
            i,j,
            ilen=haystack.size()-needle.size(),
            jlen=needle.size(); 
        for( i = 0; i <= ilen; i++){
            for( j = 0; j < jlen; j++)
                if(haystack[i+j]!=needle[j])
                    goto A;
            return i;
            A:;
        }
        return -1;
    }
};

puck

class Solution
{
  public:
    int strStr(string haystack, string needle)
    {
        std::size_t size_a{haystack.size()};
        std::size_t size_b{needle.size()};

        if (0 == size_b)
        {
            return 0;
        }

        bool flag{};

        for (int i{}; i < size_a; ++i)
        {
            if (haystack.at(i) == needle.at(0))
            {
                flag = true;

                for (int j{1}; j < size_b; ++j)
                {
                    if (i + j >= size_a || haystack.at(i + j) != needle.at(j))
                    {
                        flag = false;
                        break;
                    }
                }

                if (flag)
                {
                    return i;
                }
            }
        }

        return -1;
    }
};

823. Binary Trees With Factors@2018/06/23

196. 删除重复的电子邮箱@2018/06/23

北河

delete from Person where id in (select c.id from (select a.id from Person a  join Person b on a.Email = b.Email and a.Id > b.Id) c);

48. 旋转图像@2018/06/24

jzf

  • 4ms
class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        
        int tmp;
        for(size_t i=0; i<matrix.size();i++)
        {
            for(size_t j=i+1;j<matrix.size();j++)
            {
                
                tmp =matrix[i][j];
                matrix[i][j] =matrix[j][i];
                matrix[j][i] =tmp;
            }
        }
        for(size_t i =0;i<matrix.size();i++)
        {
            reverse(matrix[i].begin(),matrix[i].end());
        }
    }
};

kiritow

class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        int n = matrix.size();
        if (n % 2) // odd number, easy
        {
            int mid = n / 2;

            for (int dis = 1; dis <= mid; dis++)
            {
                // do chain swap at distance:dis
                int swap_n = 2 * dis + 1;
                // save right col
                vector<int> tvec;
                int begin_pos = mid - dis;
                for (int i = 0; i < swap_n; i++)
                {
                    tvec.push_back(matrix[begin_pos + i][mid + dis]);
                }
                // start rotate
                // RIGHT <- UPPER
                for (int i = 0; i < swap_n; i++)
                {
                    //printf("matrix[%d][%d]<-matrix[%d][%d]\n", begin_pos + i, mid + dis, mid - dis, begin_pos + i);
                    matrix[begin_pos + i][mid + dis] = matrix[mid - dis][begin_pos + i];
                }
                // UPPER <- LEFT
                for (int i = 0; i < swap_n; i++)
                {
                    //printf("matrix[%d][%d]<-matrix[%d][%d]\n", mid - dis, begin_pos + i, begin_pos + i, mid - dis);
                    matrix[mid - dis][begin_pos + (swap_n - i - 1)] = matrix[begin_pos + i][mid - dis];
                }
                // LEFT <- DOWNER
                for (int i = 0; i < swap_n; i++)
                {
                    //printf("matrix[%d][%d]<-matrix[%d][%d]\n", begin_pos + i, mid - dis, mid + dis, begin_pos + i);
                    matrix[begin_pos + i][mid - dis] = matrix[mid + dis][begin_pos + i];
                }
                // DOWNER <- TEMP
                for (int i = 0; i < swap_n; i++)
                {
                    //printf("matrix[%d][%d]<-tvec[%d]\n", mid + dis, begin_pos + i, i);
                    matrix[mid + dis][begin_pos + (swap_n - i - 1)] = tvec[i];
                }

                // debug
                //print(matrix);
            }
        }
        else // oh, this stuff sucks.
        {
            int mid = n / 2 ;

            for (int dis = 1; dis <= mid ; dis++)
            {
                // do chain swap at distance:dis
                int swap_n = 2 * dis;
                // save right col
                vector<int> tvec;
                int begin_pos = mid - dis;
                for (int i = 0; i < swap_n; i++)
                {
                    tvec.push_back(matrix[begin_pos + i][mid + dis - 1]);
                }
                // start rotate
                // RIGHT <- UPPER
                for (int i = 0; i < swap_n; i++)
                {
                    //printf("matrix[%d][%d]<-matrix[%d][%d]\n", begin_pos + i, mid + dis, mid - dis, begin_pos + i);
                    matrix[begin_pos + i][mid + dis - 1] = matrix[mid - dis][begin_pos + i];
                }
                // UPPER <- LEFT
                for (int i = 0; i < swap_n; i++)
                {
                    //printf("matrix[%d][%d]<-matrix[%d][%d]\n", mid - dis, begin_pos + i, begin_pos + i, mid - dis);
                    matrix[mid - dis][begin_pos + (swap_n - i - 1)] = matrix[begin_pos + i][mid - dis];
                }
                // LEFT <- DOWNER
                for (int i = 0; i < swap_n; i++)
                {
                    //printf("matrix[%d][%d]<-matrix[%d][%d]\n", begin_pos + i, mid - dis, mid + dis, begin_pos + i);
                    matrix[begin_pos + i][mid - dis] = matrix[mid + dis -1][begin_pos + i];
                }
                // DOWNER <- TEMP
                for (int i = 0; i < swap_n; i++)
                {
                    //printf("matrix[%d][%d]<-tvec[%d]\n", mid + dis, begin_pos + i, i);
                    matrix[mid + dis -1][begin_pos + (swap_n - i - 1)] = tvec[i];
                }

                // debug
                //print(matrix);
            }
        }
    }
};

puck

#include <algorithm>

class Solution
{
  public:
    void rotate(vector<vector<int>> &matrix)
    {
        auto n = matrix.size();
        auto max = n - 1;
        auto half = n / 2;

        for (int i{}; i < half; ++i)
        {
            for (int j{}; j < half; ++j)
            {
                std::swap(matrix[i][j], matrix[j][max - i]);
                std::swap(matrix[i][j], matrix[max - i][max - j]);
                std::swap(matrix[i][j], matrix[max - j][i]);
            }
        }

        if (n == 2 * half + 1)
        {
            for (int i{}; i < half; ++i)
            {
                std::swap(matrix[i][half], matrix[half][max - i]);
                std::swap(matrix[i][half], matrix[max - i][half]);
                std::swap(matrix[i][half], matrix[half][i]);
            }
        }
    }
};

4. 两个排序数组的中位数@2018/06/24

种子 似乎不符合复杂度限制

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        copy(nums2.begin(),nums2.end(),back_inserter(nums1));
        sort(nums1.begin(),nums1.end());
        return nums1.size()%2?\
            double(nums1[nums1.size()/2]):\
            double(nums1[nums1.size()/2]+nums1[nums1.size()/2-1])/2;
    }
};

北河 48ms

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        std::multiset<int> v;
        copy(nums1.begin(), nums1.end(), inserter(v, v.begin()));
        copy(nums2.begin(), nums2.end(), inserter(v, v.begin()));
        std::multiset<int>::iterator p, q;
        p = q = v.begin();
        return v.size() % 2 == 0 ? ((double)*(advance(p, v.size() / 2 - 1), p) + (double)*(advance(q, v.size() / 2), q))/ 2 : (double)*(advance(p, v.size() / 2), p);
    }
};

kiritow

#include <algorithm>
class Solution {
public:
    void forward_until(vector<int>& nums1, vector<int>& nums2,
        int lenA,int lenB,
        int& idxA, int& idxB, int& passed, int midLen)
    {
        while (idxA < lenA&&idxB < lenB && passed < midLen)
        {
            if (nums1[idxA] < nums2[idxB])
            {
                idxA++;
                passed++;
            }
            else
            {
                idxB++;
                passed++;
            }
        }
        while (idxA < lenA&&passed < midLen)
        {
            idxA++;
            passed++;
        }
        while (idxB < lenB&&passed < midLen)
        {
            idxB++;
            passed++;
        }
    }

    int getCurrent(vector<int>& nums1, vector<int>& nums2, 
        int lenA,int lenB,
        int idxA, int idxB)
    {
        if (idxA < lenA&&idxB < lenB)
        {
            return std::min(nums1[idxA], nums2[idxB]);
        }
        else if (idxA < lenA)
        {
            return nums1[idxA];
        }
        else
        {
            return nums2[idxB];
        }
    }

    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int lenA = nums1.size();
        int lenB = nums2.size();
        int sumLen = lenA + lenB;
        int midLen = sumLen / 2 - (1 - (sumLen % 2));
        int idxA = 0;
        int idxB = 0;
        int passed = 0;
        
        forward_until(nums1, nums2, lenA, lenB, idxA, idxB, passed, midLen);

        if (sumLen % 2)
        {
            return getCurrent(nums1, nums2, lenA, lenB, idxA, idxB);
        }
        else
        {
            int step1 = getCurrent(nums1, nums2, lenA, lenB, idxA, idxB);
            
            forward_until(nums1, nums2, lenA, lenB, idxA, idxB, passed, midLen + 1);
            
            int step2 = getCurrent(nums1, nums2, lenA, lenB, idxA, idxB);

            return (step1 + step2) / 2.0;
        }
    }
};

jzf

算了,我就算是抄上边几个的吧。

小白

  • 第一版 40ms

class Solution {
public:

    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
            vector<int> ab;

	std::merge(nums1.begin(), nums1.end(), nums2.begin(), nums2.end(), std::back_inserter(ab));

	return (double(ab[(ab.size() >> 1) - !(ab.size() & 1)]) + double(ab[(ab.size() >> 1)])) *0.5;
    }
};
  • 第二版
class Solution {
public:

    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
            vector<int> ab;

	std::merge(nums1.begin(), nums1.end(), nums2.begin(), nums2.end(), std::back_inserter(ab));

	return (double(ab[(ab.size() >> 1) - !(ab.size() & 1)]) + double(ab[(ab.size() >> 1)])) *0.5;
    }
};
  • 第三版 40ms

class Solution {

public:

    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {

        vector<int> ab;

        ab.reserve(nums1.size() + nums2.size());

	std::merge(nums1.begin(), nums1.end(), nums2.begin(), nums2.end(), std::back_inserter(ab));

	return double(ab[(ab.size() >> 1) - !(ab.size() & 1)] + ab[(ab.size() >> 1)]) * 0.5;

    }

};

总结

1北河和种子的体现了使用STL的巨大优势利用现有的工具确实好很多。

而我在解题的过程中出现了自创轮子没本事放弃和不熟悉STL等问题

2算法还是要学的STL的复杂度也要会分析

知识点

1 std::merge 2copy

724. 寻找数组的中心索引@2018/06/25

jzf 28ms

class Solution {
public:
    int pivotIndex(vector<int>& nums) {
        vector<int>::iterator iter;
        int sum =0;
        int ret =-1;
        for(iter =nums.begin();iter!=nums.end();iter++)
        {
            sum+=*iter;
        }
        
        int tmp =0;
        
        for(size_t i=0;i<nums.size();i++)
        {
            if((sum -nums[i]-tmp)==tmp)
            {
                ret =i;
                break;
            }
            tmp+=nums[i];
        }
        return ret;
    }
};

羽柔子

var pivotIndex = function(nums) {
    var r = 0,l=0,len = nums.length;
    if(len<2)return -1;
    for(
        var i = 1;
        i < len;
        i++
    )r += nums[i];
    for(
        var i=0;
        l!=r && i<len;
    ){
        l+=nums[i];
        i++;
        r-=nums[i];
    }
    return i>=len?-1:i;
};

class Solution {
public:
    int pivotIndex(vector<int>& nums) {
        int  r = 0,l=0,len = nums.size(),i;
        if(len<2)return -1;
    for( i = 1; i < len; i++ )r += nums[i];
    for(i=0; l!=r && i<len;){
        l+=nums[i];
        i++;
        r-=nums[i];
    }
    return i>=len?-1:i;
    }
};

puck

#include <algorithm>

class Solution
{
public:
    int pivotIndex(vector<int> &nums)
    {
        int n{-1};
        auto iter = std::find_if(nums.begin(), nums.end(), [&](const int a) {
            return ++n, std::accumulate(nums.begin(), nums.begin() + n, 0) ==
                            std::accumulate(nums.begin() + n + 1, nums.end(), 0);
        });

        if (iter == nums.end())
        {
            return -1;
        }
        return iter - nums.begin();
    }
};

小白


5. 最长回文子串@2018/06/25

jzf

  • 第一版 超时
class Solution {
public:
    string longestPalindrome(string s) {
        int len =s.size();
        string retStr="";
        for(size_t i = len; i>0;i--)
        {
            for(size_t j =0;j+i<=len;j++)
            {
                    string str =s.substr(j,i);
                    string str2 =str;
                    reverse(str2.begin(),str2.end());
                    
                    if(!str.compare(str2))
                    {
                        retStr =str;
                        return retStr;
                    }

            }
        }
        return retStr;
    }
};
  • 第二版 超时
class Solution {
public:
    string longestPalindrome(string s) {
        int len =s.size();
        string retStr=s.substr(0,1);
        for(size_t i = len; i>1;i--)
        {
            for(size_t j =0;j+i<=len;j++)
            {
                    string str =s.substr(j,i);
                    string str2 =str;
                    reverse(str2.begin(),str2.end());
                    
                    if(!str.compare(str2))
                    {
                        retStr =str;
                        return retStr;
                    }

            }
        }
        return retStr;
    }
};
  • 8ms
class Solution {
public:
int  func(string &str, int n)
{
	int ret = 1;
	size_t k = 1;
	for ( ;k <= n && (n + k)<=str.size(); k++)
	{
		if (str[n - k] == str[n + k + 1])
		{
			ret ++;
		}
		else
		{
			break;
		}
	}
	return ret;
}
int  func2(string &str, int n)
{
	int ret = 1;
	size_t k = 1;
	for (; k <= n && (n + k+3) <= str.size(); k++)
	{
		if (str[n - k] == str[n + k+2])
		{
			ret++;
		}
		else
		{
			break;
		}
	}
	return ret;
}
string longestPalindrome(string s) {
	int len = s.size();
	int max = 0;
	int center = 0;
	int f = 0;
	if (len<2)
	{
		return s;
	}
	if (len == 2)
	{
		if (s[0] == s[1])
		{
			return s;
		}
		else
		{
			return s.substr(0, 1);
		}
	}

	std::vector<int> vec1;
	for (size_t i = 0; i<len - 1; i++)
	{
		if (s[i] == s[i + 1])
		{
			vec1.push_back(i);
		}
	}

	for (size_t i = 0; i<vec1.size(); i++)
	{
		int tmp = func(s, vec1[i]);
		if (tmp>max)
		{
			max = tmp;
			center = vec1[i];
			f = 1;
		}
		if (max + i>s.size())
		{
			break;
		}
	}
	std::vector<int> vec2;
	for (size_t i = 0; i<len - 2; i++)
	{
		if (s[i] == s[i + 2])
		{
			vec2.push_back(i);
		}
	}
	for (size_t i = 0; i<vec2.size(); i++)
	{
		int tmp = func2(s, vec2[i]);
		if (tmp + 1>max)
		{
			max = tmp ;
			center = vec2[i];
			f = 2;
		}
		if (max + i>s.size())
		{
			break;
		}
	}
	if (f == 0)
	{
		return s.substr(0,1);
	}
	if (f == 1)
	{
		return s.substr(center - max+1, max * 2);
	}
	if (f == 2)
	{
		return s.substr(center -max+1, max * 2 + 1);
	}
}
};

小白

  • 第一版 超时
std::pair<string::const_iterator, string::const_iterator> longestPalindrome(string::const_iterator a, string::const_iterator b)

{

	if (a==b || std::mismatch(a, b, make_reverse_iterator(b)).first == b)

		return std::make_pair(a, b);

	auto str1 = longestPalindrome(a + 1, b), str2 = longestPalindrome(a, b - 1);

	return (str1.second - str1.first) > (str2.second - str2.first) ? str1 : str2;

}

string longestPalindrome(const string &s) {

	auto pr = longestPalindrome(s.begin(), s.end());

	return std::string(pr.first, pr.second);

}

class Solution {
public:
    string longestPalindrome(string s) {
    auto lr_max = std::make_pair( s.crend(), s.cbegin() );
	auto lr_dist_comp = [](decltype(lr_max) a, decltype(lr_max) b) 
    {return std::distance(a.first.base(), a.second) < 
        std::distance(b.first.base(), b.second); };
	for (auto cent = lr_max; cent != std::make_pair(s.crbegin(), s.cend());             std::distance(cent.first.base(), cent.second) == 0 ? ++cent.second : (--cent.first).base() )
		lr_max = std::max(lr_max, std::mismatch((cent.first - 1), s.crend(), cent.second), lr_dist_comp);
	return std::string(lr_max.first.base(), lr_max.second);
    }
};

384. 打乱数组@2018/06/26

jzf

class Solution {
    vector<int> nums;
public:
    Solution(vector<int> nums) {
        this->nums = nums;
    }
    
    /** Resets the array to its original configuration and return it. */
    vector<int> reset() {
        return nums;
    }
    
    /** Returns a random shuffling of the array. */
    vector<int> shuffle() {
        vector<int> result(nums);
        for (int i = 0;i < result.size();i++) {
            int pos = rand()%(result.size()-i);
            swap(result[i+pos], result[i]);
        }
        return result;
    }
};

北河

class Solution {
public:
    Solution(vector<int> nums) :m_nums(nums.begin(), nums.end()) {
    }
    
    /** Resets the array to its original configuration and return it. */
    vector<int> reset() {
        return m_nums;
    }
    
    /** Returns a random shuffling of the array. */
    vector<int> shuffle() {
        vector<int> v(m_nums.begin(), m_nums.end());
        random_shuffle(v.begin(), v.end());
        return v;
    }
private:
    vector<int> m_nums;
};

总结

1 北河的STL确实知道的很多random_shuffle 惊艳了我

知识点

随机数

843. 猜猜这个单词@2018/06/26

北河


class Solution {
    vector<int> nums;
public:
    Solution(vector<int> nums) {
        this->nums = nums;
    }
    
    /** Resets the array to its original configuration and return it. */
    vector<int> reset() {
        return nums;
    }
    
    /** Returns a random shuffling of the array. */
    vector<int> shuffle() {
        vector<int> result(nums);
        for (int i = 0;i < result.size();i++) {
            int pos = rand()%(result.size()-i);
            swap(result[i+pos], result[i]);
        }
        return result;
    }
};

6. Z字形变换@2018/06/26

jzf


180. 连续出现的数字@2018/06/26

jzf

select distinct s1.Num as ConsecutiveNums from Logs as s1 ,Logs as s2,Logs as s3 
 where(( (s1.id= s2.id-1 and s1.id =s3.id-2)
        ||(s1.id =s2.id+1 and s1.id =s3.id-1)
        ||(s1.id =s2.id+2 and s1.id =s3.id+1))
       and(s1.Num =s2.Num and s1.Num =s3.Num))

7. 反转整数@2018/06/27

jzf

  • 第一版
class Solution {
public:
    int reverse(int x) {
        char str[16]={0};
        sprintf(str,"%d",x);
        string s =str;
        if(s[0]=='-')
        {
            std::reverse(s.begin()+1,s.end());
        }
        else
        {
            std::reverse(s.begin(),s.end());
        }
        long ret =atol(s.c_str());
        
        if(ret >INT_MAX||ret<INT_MIN)
        {
            return 0;
        }
        return  ret;
    }
};
  • 第二版 抄 ,我很喜欢这个解法
class Solution {
public:
    int reverse(int x) {
        long long res = 0;
        while (x != 0) {
            res = res * 10 + x % 10;
            x /= 10;
        }
        return (res < INT_MIN || res > INT_MAX) ? 0 : res;
    }
};
  • 第三版

小白

  • 第一版 出错
class Solution {
public:
int reverse(int x) {

	char str[12], *p = str + sprintf(str, "%d", x);

	std::reverse(str + (x < 0), p);

	int r = strtol(str, NULL, 10);

	return errno == ERANGE ? (errno = 0) : r;

}
};
  • 第二版
int reverse(int x) {
        auto str = to_string(x);
	std::reverse(str.begin(), str.end());
	try
	{
		return str.back() == '-' ? -std::stoi(str): std::stoi(str);
	}
	catch (...)
	{
		return 0;
	}
 }

总结

1他这边用 strtol 和spritnf("%ld")出错 原因不知

知识点

1这边atoi strtoi 遇见不合适的字符会跳过,和停止

147. 对链表进行插入排序@2018/06/27

北河 16ms

class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        list<int> v;
        ListNode *p = head;
        while (p) { v.push_back(p->val); p = p->next;}
        v.sort();
        p = head;
        for (list<int>::iterator it = v.begin(); it != v.end(); ++it, p = p->next) {
            p->val = *it;
        }
        return head;
    }
};

jzf

class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        ListNode* node =head;
        if(head ==NULL)
        {
            return head;
        }
        vector<ListNode*> vec;
        while(node != NULL)
        {
            vec.push_back(node);
            node =node->next;
        }
        sort(vec.begin(),vec.end(),[](ListNode*a,ListNode*b){return a->val <b->val;});
        for(auto iter =vec.begin();iter!= vec.end();iter++)
        {
            if(iter==vec.end()-1)
            {
                (*iter)->next =NULL;
                break;
            }
            (*iter)->next =*(iter+1);
            
        }
        return *vec.begin();
    }
};

puck


class Solution
{
  public:
    ListNode *insertionSortList(ListNode *head)
    {
        if (nullptr == head)
        {
            return nullptr;
        }
        
        ListNode *fast{head->next};
        ListNode *slow{head};
        ListNode *new_head{head};
        ListNode *tmp[2]{};

        while (nullptr != fast)
        {
            if (slow->val > fast->val)
            {
                // delete the node
                slow->next = fast->next;

                if (new_head->val > fast->val)
                {
                    fast->next = new_head;
                    new_head = fast;
                }
                else
                {
                    tmp[0] = new_head;
                    tmp[1] = new_head->next;
                    while (nullptr != tmp[1])
                    {
                        if (tmp[1]->val > fast->val)
                        {
                            fast->next = tmp[1];
                            tmp[0]->next = fast;
                            break;
                        }
                        tmp[0] = tmp[1];
                        tmp[1] = tmp[1]->next;
                    }
                }
            }
            
            slow = fast;
            fast = fast->next;
        }

        return new_head;
    }
};

828. 独特字符串@2018/06/28

北河


jzf

  • 第一版超时
class Solution {
public:
int uniqueLetterString(string S) {
	int sum = 0;
    vector<pair<int,string>> vec;
    for(size_t i =0;i<S.size();i++)
    {
        vector<pair<int,string>> vecTmp;
        vecTmp =vec;
        vec.clear();
        string str=S.substr(i,1);
        vec.push_back(make_pair(1,str));
        sum++;
        if(i ==0)
        {
            continue;
        }
        for(size_t j=0;j<i;j++)
        {
            int a =count(vecTmp[j].second.begin(),vecTmp[j].second.end(),S[i]);
            int b =0;
            if(a==0)
            {
                
                b =vecTmp[j].first+1;
                vec.push_back(make_pair(b,vecTmp[j].second+str));
            }
            else
            {
              if(a==1)
              {
                b =vecTmp[j].first-1;
               }
               else
               {
                   b =vecTmp[j].first;
               }
                vec.push_back(make_pair(b,vecTmp[j].second+str));
            }
            sum+=b;
        }
  
    }
	return sum;
}
};
  • 第二版超时

class Solution {
public:
int uniqueLetterString(string S) {
	int sum = 0;
    vector<pair<int,string>> vec;
    for(size_t i =0;i<S.size();i++)
    {
       
        string str=S.substr(i,1);
        vec.push_back(make_pair(1,str));
        sum++;
        if(i ==0)
        {
            continue;
        }
        for(size_t j=0;j<i;j++)
        {
            int a =count(vec[j].second.begin(),vec[j].second.end(),S[i]);
            if(a==0)
            {
                vec[j].second+=str;
                vec[j].first+=1;
                 sum+= vec[j].first;
            }
            else
            {
                if(a ==1)
                {
                    vec[j].first-=1;
                }
                vec[j].second+=str;
                sum+= vec[j].first;
            }
        }
  
    }
	return sum;
}
};

puck

#include <algorithm>
#include <unordered_map>

class Solution
{
public:
	int uniqueLetterString(string S)
	{
		std::size_t sz = S.size();
		int result{};

		auto ed = S.end();
		bool flg{true};
		for (auto iter{ S.begin() }; iter != ed; ++iter)
		{
			for (auto ite2{ 1 + iter }; flg; ++ite2)
			{
				if (ite2 == ed)
				{
					flg = false;
				}
				result += uniqueNum(string(iter, ite2));
			}
			flg = true;
		}

		return result;
	}

private:
	int uniqueNum(string s)
	{
		//std::unordered_map<char, int> map;
		//for (string::value_type ch : s)
		//{
		//	++map[ch];
		//}

		//int num{};
		//for (auto &pair : map)
		//{
		//	if (1 == pair.second)
		//	{
		//		++num;
		//	}
		//}

		//return num;
		
		short a[128]{};

		for (string::value_type ch : s)
		{
			++a[ch];
		}

		return std::count(std::begin(a), std::end(a), 1);
	}
};

693. 交替位二进制数@2018/06/29

jzf

  • 第一版 错误
class Solution {
public:
    bool hasAlternatingBits(int n) {
       // #define IS_TARGET(x)  ((x&0xaaaaaaaa)&&(x&0x55555555))
        int x =n;
        
        if( ((x&0xaaaaaaaa)==x)&&((x|0xaaaaaaaa)==0xaaaaaaaa))
        {
            int x =~n;
            if( ((x&0x55555555)==x)&&((x|0x55555555)==0x55555555))
           {
               return true;
           }
            else
            {
                return false;
            }
        }
        
        if( ((x&0x55555555)==x)&&((x|0x55555555)==0x55555555))
        {
            int x =~n; 
             if( ((x&0xaaaaaaaa)==x)&&((x|0xaaaaaaaa)==0xaaaaaaaa))
             {
                 return true;
             }
            else
            {
                return false;
            }
        }
        return false;
    }
};
  • 第二版 0s
class Solution {
public:
    bool hasAlternatingBits(int n) {
        
        int tmp=0;
        for(size_t i= n&1?0:1;i<31;)
        {
            tmp |=1<<i;
            if(tmp>n)
            {
                return false;
            }
            else if(tmp ==n)
            {
                return true;
            }
            i +=2;
        }
  
         return false;

    }
};

总结

1 想通过按位与等方式解决问题的时候,对于异或同或之类的转换忘记了,结果绕了很大的弯子。数学还是要学一学的。

2那个神奇的代码对提升速度真的很有效.

63. 不同路径 II@2018/06/30

北河 0ms


static auto XXX = []() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    return 0;
}();

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        int m = obstacleGrid.size();
        int n = obstacleGrid[0].size();
        int v[m][n];
        memset(v, 0, m * n * sizeof(int));
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (obstacleGrid[i][j] != 0) {
                    continue;
                }
                if (i == 0 && j != 0) {
                    v[i][j] = v[i][j - 1];
                } else if (j == 0 && i != 0) {
                    v[i][j] = v[i - 1][j];
                } else if ( i != 0 && j != 0) {
                    v[i][j] += obstacleGrid[i - 1][j] > 0 ? 0 : v[i - 1][j];
                    v[i][j] += obstacleGrid[i][j - 1] > 0 ? 0 : v[i][j - 1];
                } else {
                   v[i][j] = 1;
                }
            }
        }
        return v[m - 1][n - 1];
    }
};

jzf

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
       int dp[101] ={0};
        for(int i =0;i<obstacleGrid.size();i++)
        {
            for(int j =0;j<obstacleGrid[i].size();j++)
            {
                if(i==0 &&j==0 )
                {
                    dp[j]=obstacleGrid[i][j]?0:1;
                }
                else if(j==0)
                {
                    dp[j]=obstacleGrid[i][j]?0:dp[j];
                }
                else
                {
                     dp[j]=obstacleGrid[i][j]?0:dp[j]+dp[j-1];
                }
            }
        }
        return dp[(*(obstacleGrid.end()-1)).size()-1];
    }
};

总结

1先解决的718我使用了暴力超时了在摸索的过程中我画了二叉树的图和一个数组A和B为列表项的二维表。发现二维表可以很好的表示关系

2根据二维表的规律我学习了动态规划但是还是多次失败了其原因在于边界处理十分困难如何处理二维表的边界上的计算公式很头疼。

718. 最长重复子数组@2018/07/01

jzf

  • 第一版 超时
class Solution {
public:
    int findLength(vector<int>& A, vector<int>& B) {
        int max=0;
      
     
        for(size_t i =0 ;i<A.size();i++)
        {  
           
            for(size_t j=0;j<B.size();j++)
            {
                 int tmp =0;
                size_t k =i;
                size_t x =j;
                while(k<A.size()&&x<B.size())
                {     
                    if(A[k]!=B[x]) 
                    {
                          break;
                    }
                    tmp++;
                    k++;
                    x++;
                 }
                if(tmp>max)
                {
                    max =tmp;
                }
            }
        }
        return max;
    }
};
  • 第二版 dp

北河

static auto XX = []() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    return 0;
}();

class Solution {
public:
    int findLength(vector<int>& A, vector<int>& B) {
        vector<int> dp(1001);
        int m = 0;
        for (int i = A.size() - 1; i >= 0; --i) {
            for (size_t j = 0; j < B.size(); ++j) {
                if (A[i] == B[j]) {
                    dp[j] = dp[j + 1] + 1;
                    if (dp[j] > m) {
                        m = dp[j];
                    }
                } else {
                    dp[j] = 0;
                }
            }
        }
        return m;
    }
};

406. 根据身高重建队列@2018/07/02 未备份

455. 分发饼干@2018/07/03

jzf

class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        sort(g.begin(),g.end());
        sort(s.begin(),s.end());
        
        int j =0;
        int i=0;
        int t =0;
        for(;i<std::min(g.size(),s.size());i++)
        {
            for(;j<s.size();)
            {
                if(g[i] <=s[j])
                {
                    t++;   
                    j++;
                    break;
                }
                j++;
            }
        }
        return t;
    }
};

北河

738.单调递增的数字@2018/07/04

北河


jzf


class Solution {
public:
    int turn2Int(char *p)
    {
        int ret=0;
        while(*p !=0)
        {
            ret= ret*10+(*p-'0');
            p++;
        }
        return ret;
    }
    void tostr(int tmp,char* p)
    {
        int s =1;
        int q =tmp;
        for(;q>10;q/=10)
        {
            s*=10;
        }
        for(;s>0;s/=10)
        {
            *(p++)=tmp/s+'0';
            tmp=tmp%s;
        }
    }
    int monotoneIncreasingDigits(int N) {
       // tostring(N);
        char str[11]={0};
        tostr(N,str);
        
        int t=0;
        for(size_t i=0;i<11 &&str[i]!=0;i++)
        {
            if(str[i] > str[i+1])
            {
                t =i;
                break;
            }
        }
        if(t==0)
        {
            str[0]-=1;
            for(int i= t+1;i<11 &&str[i]!=0;i++)
            {
                str[i] ='9';
            }
             return turn2Int(str+t);
        }
        else if(str[t+1]==0)
        {
            return  N;cout<<12;
        }
        else
        {
            int tmp =t;
            while(t>0)
            {
                    if(str[t]>str[t-1])
                    {
                         str[t]-=1;
                        for(int i= t+1;i<11 &&str[i]!=0;i++)
                        {
                            str[i] ='9';
                        }
                        return turn2Int(str);
                    }
                t--;
            }
            
            if(t==0)
            {
               
                  str[0]-=1;
                for(int i= t+1;i<11 &&str[i]!=0;i++)
                 {
                    str[i] ='9';
                }
                return turn2Int(str+t);
            }
           
        }
        return turn2Int(str+t);
    }
};

313. 超级丑数@2018/07/05 无人做

20. 有效的括号@2018/07/06

羽柔子

var isValid = function (s) {
    var l = new Array();
    return s.split("").every(e => {
        switch (e) {
            case '(': return l.push(1);
            case ')': return l.pop() == 1;
            case '{': return l.push(2);
            case '}': return l.pop() == 2;
            case '[': return l.push(3);
            case ']': return l.pop() == 3;
        };
    }) ? !l.length : false;
};

jzf

  • 第一版错误
class Solution {
public:
    bool isClosed(char c, char dst)
 {
	 switch (c)
	 {
	 case '[':
		 return dst == ']';
	 case '{':
		 return dst == '}';
	 case '(':
		 return dst == ')';
	 default:
		 return false;
	 }
 }
 bool isOpen(char c)
 {
	 switch (c)
	 {
	 case '[':

	 case '{':

	 case '(':
		 return true;
	 default:
		 return false;
	 }
 }
 bool check(size_t &i, string &s)
 {
	 size_t j = i + 1;
     bool ret=false;
	 for (; j<s.size(); j++)
	 {
		 if (isClosed(s[i], s[j]) && ((j - i) & 1) == 1)
		 {
             ret =true;
			 for (size_t k = (j - i-1)/2; k>0; k--)
			 {
                 
				 if (!isClosed(s[i + k], s[j - k]))
				 {
					 return false;
				 }
			 }
             break;
		 }
	 }
	 i = j;
	 return ret;
 }
 bool isValid(string s) {
	 // '[''{''('')''}'']'
	 for (size_t i = 0; i<s.size(); i++)
	 {
		 if (isOpen(s[i]) && (i & 1) == 0)
		 {
			 if (!check(i, s))
			 {
				 return false;
			 }
		 }
		 else
		 {
			 return false;
		 }
	 }
	 return true;
 }
};
  • 第二版
class Solution {
public:
    bool isClosed(char c, char dst)
 {
	 switch (c)
	 {
	 case '[':
		 return dst == ']';
	 case '{':
		 return dst == '}';
	 case '(':
		 return dst == ')';
	 default:
		 return false;
	 }
 }
 bool isOpen(char c)
 {
	 switch (c)
	 {
	 case '[':

	 case '{':

	 case '(':
		 return true;
	 default:
		 return false;
	 }
 }

 bool isValid(string s) {
	 // '[''{''('')''}'']'
     bool ret =false; 
     int tmp =0; 
    while(s.size()!=tmp)
    {
        tmp =s.size();
        for(int i=0;i<tmp-1;i++)
        {
            if(isClosed(s[i],s[i+1]))
            {
                s.erase(i,2);
                break;
            }
        }
    }
     return tmp==0?true:false;
 }
};

三浪

typedef struct tagStack
{
	char * p;
	int iPos;
}Stack;

void BulidStack(Stack *pStack, int size)
{
	pStack->p = (char *)malloc(size * sizeof(char));
	memset(pStack->p, 0, size);
	pStack->iPos= 0;
}

void DestroyStack(Stack *pStack)
{
	free(pStack->p);
}

int Push(Stack *pStack, char ch)
{
	if (pStack->iPos >= 0)
	{
		*(pStack->p + pStack->iPos) = ch;
		++(pStack->iPos);
		return 0;
	}
	return -1;
}

int Pop(Stack *pStack)
{
	--(pStack->iPos);
	if (pStack->iPos >= 0)
	{
		*(pStack->p + pStack->iPos) = '\0';
		return 0;
	}
	return -1;
}
char GetPairChar(char ch)
{
	switch (ch)
	{
		case ')':
			return '(';
		case '}':
			return '{';

		case ']':
			return '[';
		default:
			return '\0';
	}
}

bool IsPush(char ch)
{
	if (ch == '(' || ch == '{' || ch == '[')
	{
		return true;
	}
	return false;
}

bool isValid(char *s)
{
	if ('\0' == *s)
	{
		return true;
	}
	int n = 0;
	char chPre = *s;
	if (!IsPush(chPre))
	{
		return false;
	}

	Stack myStack;
	BulidStack(&myStack, strlen(s) + 1);
	while (*s != '\0')
	{
		char chCur = *s;
		if (IsPush(chCur))
		{
			if (0 != Push(&myStack, chCur))
			{
				return false;
			}
		}
		else
		{
			if ((myStack.iPos >= 1) && 
			(myStack.p[myStack.iPos - 1] == GetPairChar(chCur)))
			{
				if (0 != Pop(&myStack))	
				{
					return false;
				}
			}
			else
			{

				if (0 != Push(&myStack, chCur))
				{
					return false;
				}
			}
		}
		chPre = *s;
		++s;
	}
	if (0 == myStack.iPos)
	{
		DestroyStack(&myStack);
		return true;
	}
	else
	{
		DestroyStack(&myStack);
		return false;
	}

}

总结

1我在做这道题的时候出现了许多次的分析失误疏忽了一些情形。 2发现 s.size()的返回类型是size_t ,遇到了一个比较悲惨的越界错误。 size_t是unsigned int类型的 当 for(int i=0; i<tmp -1;i++)中的tmp = 0时就出现了大bug;