字符串数组的去重

字符串数组的去重

输入

第一行为个数n,之后n行每行一个字符串(1<n<50000)

输出

输出不重复的字符串的个数

输入样例

3
aaaa
AAAa
aaaa

输出样例

2

 我一开始是这样写的,结果在oj提交的时候第三个测试用例超时了。

#include <bits/stdc++.h>
using namespace std;
int main()
{
    map<string,int> Map;        
    int n;
    cin >> n;
    string s[n];   
    // 输入n行字符
    for(int i=0;i<n;i++)
    {
        cin >> s[i];
    }
    int Count = 0;
    for(string word:s)  
    //for-each循环,将字符串数组s中的每个字符串依次取出,赋值给word
    {
        if(Map[word]==0)
        {
            Count++;   //统计字符串数组中不同字符串的数目
        }
        Map[word] = 1;  
        /*这里没有使用Map[word]++;
         *因为我们只需要知道这个字符出现过就行了,
         *并不需要记录每个字符串出现的次数,所以直接赋值为1
         */
    }
    cout << Count;
    return 0;
}

于是,在仔细分析代码之后,我觉得是cin造成了我的代码超时,然后我百度了一下解决cin造成超时的方法。

AC代码如下:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    ios::sync_with_stdio(false); //取消cin和stdin的同步
    map<string,int> Map;        
    int n;
    cin >> n;
    string s[n];   
    // 输入n行字符
    for(int i=0;i<n;i++)
    {
        cin >> s[i];
    }
    int Count = 0;
    for(string word:s)  
    //for-each循环,将字符串数组s中的每个字符串依次取出,赋值给word
    {
        if(Map[word]==0)
        {
            Count++;   //统计字符串数组中不同字符串的数目
        }
        Map[word] = 1;  
        /*这里没有使用Map[word]++;
         *因为我们只需要知道这个字符出现过就行了,
         *并不需要记录每个字符串出现的次数,所以直接赋值为1
         */
    }
    cout << Count;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42449444/article/details/83186136