PAT Advanced 1050 String Subtraction (20) [Hash Hash]

topic

Given two strings S1 and S2, S = S1 – S2 is defined to be the remaining string afer 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.

The meaning of problems

  1. Input s1, s2, printed s = s1-s2 (ie: not appear in the print s1 s2 characters)
  2. s1, s2 average length <= 10 ^ 4, all characters are characters in the ASCII table, indicates the end of input newline

Topic analysis

  1. Defined int asc [256], record s2 character occurrences.
  2. Traversing s1, if asc [s1 [i]]> 0, the instructions that appear in s2, not printed

Knowledge Point

  1. Mark all ASCII code length of the array can be set to 256
  2. Receiving the entire line using character array
char ca[10001];
cin.getline(ca,10001);//不可以修改为strlen(ca),因为strlen是获取已填充字符长度

Code

Code 01(string)

#include <iostream>
using namespace std;
int main(int argc, char * argv[]) {
    string s1,s2;
    getline(cin,s1);
    getline(cin,s2);
    int asc[256]= {0};
    for(int i=0; i<s2.length(); i++) {
        asc[s2[i]]++;
    }
    for(int i=0; i<s1.length(); i++) {
        if(asc[s1[i]]>0)continue;
        printf("%c",s1[i]);
    }
    return 0;
}

Code 02(char array)

#include <iostream>
#include <cstring> 
using namespace std;
int main(int argc, char * argv[]) {
    char s1[10001],s2[10001];
    cin.getline(s1,10001);
    cin.getline(s2,10001);
    int asc[256]= {0};
    int len1=strlen(s1),len2=strlen(s2);//如果直接在for条件中写strlen()容易引起超时 
    for(int i=0; i<len2; i++) asc[s2[i]]++;
    for(int i=0; i<len1; i++) {
        if(asc[s1[i]]>0)continue;
        printf("%c",s1[i]);
    }
    return 0;
}


Guess you like

Origin www.cnblogs.com/houzm/p/12238628.html