zoukankan      html  css  js  c++  java
  • Anagrams leetcode java

    题目:

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

    Note: All inputs will be in lower-case.

    题解:

    这道题看所给的字符串数组里面有多少个是同一个变形词变的。这道题同样使用HashMap来帮助存老值和新值,以及帮忙判断是否是变形词。

    首先对每个string转换成char array然后排下序,HashMap里面的key存sort后的词,value存原始的词。然后如果这个排好序的词没在HashMap中出现过,那么就把这个sorted word和unsortedword put进HashMap里面。如果一个sorted word是在HashMap里面存在过的,说明这个词肯定是个变形词,除了把这个词加入到返回结果中,还需要把之前第一个存进HashMap里面的value存入result中。

    代码如下:

     1  public ArrayList<String> anagrams(String[] strs) {
     2      ArrayList<String> result=new ArrayList<String>();
     3      
     4      if (strs==null||strs.length==0)
     5          return result;
     6      
     7      HashMap<String,ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();
     8      
     9      for (String s:strs){
    10          char[] temp=s.toCharArray();
    11          Arrays.sort(temp);
    12          String tempStr=new String(temp);
    13          
    14          if (hm.containsKey(tempStr)){
    15              if(hm.get(tempStr).size() == 1)
    16                 result.add(hm.get(tempStr).get(0));
    17              hm.get(tempStr).add(s);
    18              result.add(s);
    19          }else{
    20              ArrayList<String> tempList=new ArrayList<String>();
    21              tempList.add(s);
    22              hm.put(tempStr, tempList);
    23              }
    24         }
    25         return result;
    26  }

  • 相关阅读:
    大数加法、乘法实现的简单版本
    hdu 4027 Can you answer these queries?
    zoj 1610 Count the Colors
    2018 徐州赛区网赛 G. Trace
    1495 中国好区间 尺取法
    LA 3938 动态最大连续区间 线段树
    51nod 1275 连续子段的差异
    caioj 1172 poj 2823 单调队列过渡题
    数据结构和算法题
    一个通用分页类
  • 原文地址:https://www.cnblogs.com/springfor/p/3874667.html
Copyright © 2011-2022 走看看