zoukankan      html  css  js  c++  java
  • LeetCode ---Anagrams() 详解

    Notice:

    Given an array of strings, return all groups of strings that are anagrams.

    Note: All inputs will be in lower-case.

    For example:

    Input:  ["tea","and","ate","eat","den"]

    Output:   ["tea","ate","eat"]

    Interface: vector<string>anagrams(vector<string>&strs);

    解题思路:

    有相同字母构成的不同序列的单词,排过序后肯定是一样的,所以可以存放在map中,最后从map中取出value个数大于1的值,也就是字母相同构成的字母“们”

    举个例子["ate","tea","aet","eat","hgt","gf","atg","gat"]对于这个容器而言,我们先对ate字典排序,变成aet,然后放入map中,这里的map构造为

    map<string,vector<string>>

    对7个单词遍历后,map的构成如下:

    key        value[0] value[1] value[2] value[3]

    aet    ate         tea         aet         eat

    ght       hgt

    fg         gf

    agt        atg        gat

    之后遍历map,对于value个数大于1的单词“们”放入res数组中,

    最后res数组中即为那些Anagrams

     这里会输出两组 Anagrams

     1 class Solution{
     2 public:
     3   vector<string> anagrams(vector<string> &strs){
     4     map<string,vector<string>> m;
     5     vector<string> res;
     6     for(int i = 0; i < strs.size() ; i++){
     7       string s = strs[i];
     8       sort(s.begin(),s.end());//排序
     9       m[s].push_back(strs[i]);//插入map
    10     }
    11 
    12     for(map<string,vector<string>>::iterator i = m.begin(); i != m.end(); i++){
    13       if((i->second).size() > 1)
    14         for(int it = 0; it < (i->second).size();it++)
    15           res.push_back((i->second)[it]);//输出
    16     }
    17     return res;
    18   }
    19 };

    PS:必须深入理解STL中,map的用法,key-value可以取各种类型包括容器类型。size()等内建函数也是通用的。

     
     
  • 相关阅读:
    信号的调制
    是否产生latch
    带通采样定理
    傅里叶变换
    信号与傅里叶(下)
    滤波器的相位和信号的时延
    信号与傅里叶级数
    阅读应该是主动的
    Matlab笔记—函数
    网络搭建---IP地址的设置及ping的使用
  • 原文地址:https://www.cnblogs.com/134feilei/p/3833715.html
Copyright © 2011-2022 走看看