哈理工oj 1677

水题,可我做了三小时。。。

题目大意就是在一个只含有‘x’和‘y’字符的字符串中,除掉所有‘xy’对(不分前后顺序),不管‘x’和‘y’之间有没有字符,只要能凑成一对就要除掉。

一开始我就看错题意导致做了很久,后来发现,这不就是用栈搞定的题嘛。

思路:先用一个数组存下字符串,然后把字符串从头到尾往栈里面塞字符,如果栈顶元素的字符与字符串中的字符不相同,就推出栈顶元素,同时字符串中的那个字符也不塞入栈中,最后再把栈中元素全部输出即可。

代码如下:

#include 
#include 
#include 
#include 
#define maxn 1000006
using namespace std;

char str[maxn] = {};
int main()
{
    while(cin >> str)
    {
        stack book;
        int len = strlen(str);
        for(int i = 0; i < len; i++)
        {
            if(book.empty())
            {
                book.push(str[i]);
            }
            else
            {
                if(book.top() == str[i])
                {
                    book.push(str[i]);
                }
                else
                {
                    book.pop();
                }
            }
        }
        while(!book.empty())
        {
            cout << book.top();
            book.pop();
        }
        cout << endl;
        memset(str, 0, sizeof(str));
    }
}

错误代码:

#include 
#include 
#include 
#include 
#define maxn 1000006

using namespace std;

char str[maxn] = {}, rec[maxn] = {};
int main()
{
    char ch;
    int cnt = 0;
    while(~scanf("%s", &str))
    {
        stack book;
        int len = strlen(str);
        if(len == 1)
        {
            printf("%s\n", str);
            continue;
        }
        for(int i = 0; i < len; i++)
        {
            if(str[i] == 'x' && str[i + 1] == 'y')
            {
                i++;
            }
            else
            {
                book.push(str[i]);
                //printf("%c", str[i]);
            }
        }
        //printf("\n");
        int flag = 1;
        while(flag == 1)
        {
            int cnt = 1;
            rec[1] = book.top();
            book.pop();
            flag = 0;
            printf("%c", rec[1]);
            while(!book.empty())
            {
                if(rec[cnt] != book.top()) flag = 1;
                if(rec[cnt] == 'x' && book.top() == 'y')
                {
                    rec[cnt] = 0;
                    book.pop();
                }
                else
                {
                    cnt++;
                    rec[cnt] = book.top();
                    printf("%c", rec[cnt]);
                }
                if(!book.empty()) book.pop();
            }
            printf("\n*******\n");
            //printf("%d\n", book.empty());
            if(!flag) break;
            int len = strlen(rec + 1);
            printf("%d\n", len);
            for(int i = 1; i <= len; i++)
            {
                printf("%c", rec[i]);
                book.push(rec[i]);
                rec[i] = 0;
            }
            printf("\n#########\n");
        }
        printf("%s\n", rec + 1);
        memset(str, 0, sizeof(str));
        memset(rec, 0, sizeof(rec));
    }
}
/**
xyyxxx
*/

 

你可能感兴趣的:(栈)