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;
    }
};

猜你喜欢

转载自www.cnblogs.com/Tang-tangt/p/9229996.html