zoukankan      html  css  js  c++  java
  • 487 姓名去重

    原题网址:https://www.lintcode.com/problem/name-deduplication/description

    描述

    给一串名字,将他们去重之后返回。两个名字重复是说在忽略大小写的情况下是一样的。

    您在真实的面试中是否遇到过这个题?  

    样例

    给出:

    [
      "James",
      "james",
      "Bill Gates",
      "bill Gates",
      "Hello World",
      "HELLO WORLD",
      "Helloworld"
    ]
    

    返回:

    [
      "james",
      "bill gates",
      "hello world",
      "helloworld"
    ]
    

    返回名字必须都是小写字母。

    标签
    哈希表
     

    思路:创建 string——int 哈希表,key为字符串。遍历数组,将每个字符串转成小写,同时将(字符串,1)成对插入到哈希表中。【1是value,这道题不关心value只关心key,所以value可以自定义】

    遍历哈希表,将key保存在结果数组中,return出去。

     

    AC代码:

    class Solution {
    public:
        /**
         * @param names: a string array
         * @return: a string array
         */
        vector<string> nameDeduplication(vector<string> &names) {
            // write your code here
        vector<string> result;
         map<string,int> m;
         int size=names.size();
         for (int i=0;i<size;i++)
         {
             for (int j=0;j<(int)names[i].size();j++)
             {
                 names[i][j]=tolower(names[i][j]);
             }
             m.insert(pair<string,int>(names[i],1));
         }
         
         map<string,int>::iterator it=m.begin();
         for (;it!=m.end();it++)
         {
             result.push_back(it->first);
         }
         return result;
        }
    };

     

     由于本题只关心key,还可以使用C++11中的unordered_set,参考此文

    C++ STL 之 unordered_set 介绍

    C++ 头文件系列(unordered_map、unordered_set)

     

  • 相关阅读:
    OMNETPP: tictoc
    OMNETPP安装
    Unified SR
    SCM
    DC tunnel
    AIMD
    AQM
    MANAGER POJ1281 C语言
    Pascal Library C语言 UVALive3470
    The 3n + 1 problem C语言 UVA100
  • 原文地址:https://www.cnblogs.com/Tang-tangt/p/9229996.html
Copyright © 2011-2022 走看看