PAT Basic 1093. 字符串A+B
PAT Basic 1093. 字符串A+B
1. 题目描述:
给定两个字符串 \(A\) 和 \(B\),本题要求你输出 \(A+B\),即两个字符串的并集。要求先输出 \(A\),再输出 \(B\),但重复的字符必须被剔除。
2. 输入格式:
输入在两行中分别给出 \(A\) 和 \(B\),均为长度不超过 \(10^6\)的、由可见 ASCII 字符 (即码值为32~126)和空格组成的、由回车标识结束的非空字符串。
3. 输出格式:
在一行中输出题面要求的 \(A\) 和 \(B\) 的和。
4. 输入样例:
This is a sample test
to show you_How it works
5. 输出样例:
This ampletowyu_Hrk
6. 性能要求:
Code Size Limit
16 KB
Time Limit
400 ms
Memory Limit
64 MB
思路:
维护flag数组保证每种字符只输出1次即可。其他都是之前踩过的坑:
- 存储字符串的字符数组大小设为\(10^6+1+1\),即最大长度+末尾换行符+空字符。
- 因为字符串中可能含有空格符,所以不能使用scanf()读入,这里使用fgets()。
另外就是用""或{0}都会使字符数组各元素初始化为0,因为空字符'\0'的ASCII码为0,还有这里学到了空格符的ASCII码为32。
My Code:
#include <stdio.h>
#define MAX_LEN (1000000 + 1 + 1) // MAX_LEN + '\n' + '\0'
int main(void)
{
    char str1[MAX_LEN] = ""; // this will set every element to '\0', i.e. 0
    char str2[MAX_LEN] = "";
    char flag[127] = {0}; // this also will set every element to 0
    int i=0; // iterator
    
    //fgets(char * s, int size, FILE * stream)
    fgets(str1, MAX_LEN, stdin);
    fgets(str2, MAX_LEN, stdin);
    
    for(i=0; str1[i]!='\n'; ++i)
    {
        if(!flag[str1[i]])
        {
            printf("%c", str1[i]);
            flag[str1[i]] = 1;
        }
    }
    
    for(i=0; str2[i]!='\n'; ++i)
    {
        if(!flag[str2[i]])
        {
            printf("%c", str2[i]);
            flag[str2[i]] = 1;
        }
    }
    printf("\n");
    
    
//     flag[99] = 1;
//     for(i=0; i<100; ++i)
//     {
//         if(flag[i] == 0) printf("Yes!\n");
//     }
    
    //printf("%d%c%d\n", 1,32,2); // the ASCII of space is 32!
    
    return 0;
}

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号