zoukankan      html  css  js  c++  java
  • leetcode 49 Group Anagram

    lc49 Group Anagram

    逻辑很简单,就是统计字母出现次数,然后将完全相同的字符串放入同一list

    关键是怎么实现

    统计的部分,可以通过将string排序,Arrays.sort(),或者像之前int[26]一样,

    那么如何一次遍历,就能将相同字符串放入一个list呢?

    这里用到了HashMap<String, List<String>>,String为key,用来判断排序过后的str是否相同,若是相同,直接原来的str加入List<String>

    最后返回值就是把map的value转成List<List<String>>

    可以用到一个小方法:

      return new ArrayList<List<String>>(map.values())

    因为HashMap的value都是List<String>

     1 class Solution {
     2     public List<List<String>> groupAnagrams(String[] strs) {
     3         List<List<String>> res = new ArrayList<>();
     4         if(strs.length == 0)
     5             return res;
     6         HashMap<String, List<String>> map = new HashMap<>();
     7         
     8         
     9         for(int i=0; i<strs.length; i++){
    10             char[] tmp = strs[i].toCharArray();
    11             Arrays.sort(tmp);
    12             String key = String.valueOf(tmp);
    13             if(!map.containsKey(key))
    14                 map.put(key, new ArrayList<String>());
    15            map.get(key).add(strs[i]);
    16         }
    17         
    18         return new ArrayList<List<String>>(map.values());
    19     }
    20 }
  • 相关阅读:
    UVa532 Dungeon Master 三维迷宫
    6.4.2 走迷宫
    UVA 439 Knight Moves
    UVa784 Maze Exploration
    UVa657 The die is cast
    UVa572 Oil Deposits DFS求连通块
    UVa10562 Undraw the Trees
    UVa839 Not so Mobile
    327
    UVa699 The Falling Leaves
  • 原文地址:https://www.cnblogs.com/hwd9654/p/10958849.html
Copyright © 2011-2022 走看看