[LeetCode6]Anagrams

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

Note: All inputs will be in lower-case.

Analysis:

Anagrams is two strings are using the same characters.
One way to compare two strings is use sort(). e.g.
sort(str1.begin(), str1.end());
sort(str1.begin(), str1.end());
if (str1.compare(str2)==0) // when two strings are equal, the func returns 0

A more efficient way:
1. Scan the whole string vector, for each string, store to a hash map with the "ordered string" as the key. O(n).
2. Scan the whole hash map, output the values where for one key the number of value >=2. O(n)

Note:
1. We can use multimap<string, string> in c++, which allows the duplicate key values.
2. To store key-value into multimap, use ".insert(pair<key_type, value_type>(key,value))"
3. Use "pair<multimap<string,string>::iterator,multimap<string,string>::iterator> ret;" and
".equal_range()" which returns a iterator pair(ret) that the "first" is the lower bound and "second" is the upper bound, to get all the key-values pairs for one key.
4. To check the number of values in one key, use the .count(key) method.

Java

public List<String> anagrams(String[] strs) {
        List<String> result = new ArrayList<>();
        HashMap<String, Integer> anagramMap = new HashMap<String,Integer>();
        for(int i=0;i<strs.length;i++){
        	String t1 = strs[i];
        	char [] s1= t1.toCharArray();
        	Arrays.sort(s1);
        	t1 = new String(s1);
        	if(!anagramMap.containsKey(t1)){
        		anagramMap.put(t1, i);
        	}else {
				result.add(strs[i]);
				if(anagramMap.get(t1)!=-1){
					result.add(strs[anagramMap.get(t1)]);
					anagramMap.put(t1, -1);
				}
			}
        }
        return result;
    }
c++

vector<string> anagrams(vector<string> &strs) {
        vector<string> result;
    map<string,int> temp;
    for(int i=0; i<strs.size();i++){
        string str = strs[i];
        sort(str.begin(),str.end());
        if(temp.find(str) == temp.end()){
            temp[str] = 1;
        }
        else{
            temp[str]++;
        }
    }
    for(int i=0; i<strs.size();i++){
        string str = strs[i];
        sort(str.begin(),str.end());
        if(temp.find(str) != temp.end() && temp[str]>1){
            result.push_back(strs[i]);
        }
    }
    return result;
    }




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值