zoukankan      html  css  js  c++  java
  • Java for LeetCode 049 Anagrams

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

    Note: All inputs will be in lower-case.

    解题思路:首先要理解,什么是anagrams,ie。“tea”、“tae”、“aet”,然后就十分好做了,new一个hashmap,使用一个排过序的String作为key,重复了就往里面添加元素,这里出现一个小插曲,就是排序的时候不要用PriorityQueue,因为PriorityQueue是采用堆排序的,仅保证堆顶元素为优先级最高的(害了我好久)JAVA实现如下:

    	static public List<String> anagrams(String[] strs) {
    		List<String> list = new ArrayList<String>();
    		HashMap<String, List<String>> hm = new HashMap<String, List<String>>();
    		for (int i = 0; i < strs.length; i++) {
    			char [] c=strs[i].toCharArray();
    			Arrays.sort(c);
    			String sortString=new String(c);
    			if (!hm.containsKey(sortString)) 
    				hm.put(sortString.toString(), new ArrayList<String>());
    			hm.get(sortString.toString()).add(strs[i]);
    		}
    		Iterator<String> iterator = hm.keySet().iterator();
    		while (iterator.hasNext()) {
    			String key = iterator.next();
    			if (hm.get(key).size() > 1) 
    				list.addAll(hm.get(key));
    		}
    		return list;
    	}
    
  • 相关阅读:
    Wide & Deep Learning for Recommender Systems
    两个经典问题
    Vlog简介
    中文dumps显示
    用Python提取中文关键词
    【STL】算法 — partial_sort
    c字符串分割 strtok()
    JSP的声明(statement)
    layui之ajax巨坑
    jQuery 库中的 $() 是什么?(答案如下)
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4504804.html
Copyright © 2011-2022 走看看