pat 1050. String Subtraction (20)

1050. String Subtraction (20)

时间限制
10 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

Given two strings S1 and S2, S = S1 - S2 is defined to be the remaining string after taking all the characters in S2 from S1. Your task is simply to calculate S1 - S2 for any given strings. However, it might not be that simple to do it fast.

Input Specification:

Each input file contains one test case. Each case consists of two lines which gives S1 and S2, respectively. The string lengths of both strings are no more than 104. It is guaranteed that all the characters are visible ASCII codes and white space, and a new line character signals the end of a string.

Output Specification:

For each test case, print S1 - S2 in one line.

Sample Input:
They are students.
aeiou
Sample Output:
Thy r stdnts.
解:暴力卡时,后来听陈叔叔的建议,预处理了下s2,考虑这种情况,如s2=aaa,其实只是a而已,我们预处理为s2=a,可以在一定程度上降低时间复杂度。事实证明是可行的。

代码:

#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<set>
using namespace std;
int main()
{
    char s1[10000+1];
    char s2[10000+1];
    string res;
    set<char> sss;
    gets(s1);
    gets(s2);
    int len1=strlen(s1);
    int len2=strlen(s2);
    for(int i=0;i<len2;i++)   //预处理s2
        sss.insert(s2[i]);
    set<char>::iterator p;
    for(int i=0;i<len1;i++)
    {
        int flag=1;
        for(p=sss.begin();p!=sss.end();p++)
        {
            if(s1[i]==*p)
            {
                flag=0;
                break;
            }
        }
        if(flag==1)
           res.push_back(s1[i]);
    }
    cout<<res<<endl;
}

底下是改进的办法,用了set的内置函数find():

#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<set>
using namespace std;
int main()
{
    char s1[10000+1];
    char s2[10000+1];
    string res;
    set<char> sss;
    gets(s1);
    gets(s2);
    int len1=strlen(s1);
    int len2=strlen(s2);
    for(int i=0;i<len2;i++)   //预处理s2
        sss.insert(s2[i]);
    for(int i=0;i<len1;i++)
    {
        int flag=1;
        if(sss.find(s1[i])!=sss.end())
        {
            flag=0;
        }
        if(flag==1)
           res.push_back(s1[i]);
    }
    cout<<res<<endl;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted on 2015-07-19 18:50  Tob__yuhong  阅读(173)  评论(0编辑  收藏  举报

导航