zoukankan      html  css  js  c++  java
  • LeetCode 49: Anagrams

    题目描述:

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

    Note: All inputs will be in lower-case.

    思路:

    题目的意思呢,就是寻找一组字符串中,字符串使用相同数量的相同字符的两个字符串互为anagrams,把这样的字符串输出。

    明白了题目的意思,我们可以对每个字符串进行排序,然后将排序后的字符串作为该字符串的哈希值,保存每个哈希值的所有字符串。如果该哈希值的字符串的个数大于1,也就是说存在anagrams

    代码:

    class Solution {
    public:
        vector<string> anagrams(vector<string> &strs) {
    		map<string,vector<string> > map_str;
    		vector<string> vec_str;
    		for(int i =0;i<strs.size();i++){
    			string temp= strs[i];
    			sort(temp.begin(),temp.end());
    			map_str[temp].push_back(strs[i]);
    		}
    		for(map<string,vector<string> >::iterator it=map_str.begin(); it!=map_str.end(); it++){
    			for(vector<string>::iterator it2 = it->second.begin(); it2!=it->second.end() &&(it->second).size()>1; it2++){
    				vec_str.push_back(*it2);
    			}
    		}
    		return vec_str;
    	}
    };
    
  • 相关阅读:
    python 慕名函数
    python 不定长参数
    python 关键字参数
    python 传递参数
    python 函数的返回值
    python 函数的参数
    python 最简单的函数(无参无返回值)
    python 迭代器
    python 迭代器案例
    在 android 上运行 python 的方法
  • 原文地址:https://www.cnblogs.com/xiamaogeng/p/4361374.html
Copyright © 2011-2022 走看看