Chinaunix首页 | 论坛 | 博客
  • 博客访问: 255913
  • 博文数量: 170
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1709
  • 用 户 组: 普通用户
  • 注册时间: 2014-05-06 18:01
文章分类

全部博文(170)

文章存档

2016年(11)

2015年(130)

2014年(29)

分类: Java

2015-03-17 15:19:00

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

Note: All inputs will be in lower-case.


思路:

1. 从strs的第一个元素开始遍历,首先对元素进行排序得到s

2. 在map里查找s

3. 若不存在,将s以及该元素的下标存入map

4. 若存在,首先将第一次出现s时的原始字符串存入结果res,并将map[s]设置为-1(防止下次再存),再将该字符串本身存入结果res

5. 重复以上1-4步,直到遍历结束。


public List anagrams(String[] strs) {
List result=new ArrayList();
Map map=new HashMap();
int count=strs.length;
if(count<2)
return result;
for(int i=0;i char[] a=new char[strs[i].length()];
a=strs[i].toCharArray();
Arrays.sort(a);
String b=String.valueOf(a);//char数组转化为Sting 使用String.valueOf,不能使用 a.toString()。
if(!map.containsKey(b))
map.put(b,i);
else {
int index=map.get(b);
if(index>=0){
result.add(strs[index]);
map.replace(b, index, -1);
result.add(strs[i]);
}
else{
result.add(strs[i]);
}
}

}
return result;
    }

阅读(219) | 评论(0) | 转发(0) |
1

上一篇:Search a 2D Matrix

下一篇:Combinations

给主人留下些什么吧!~~