【leetcode】49. (Medium) Group Anagrams

题目链接


解题思路:
这道题的意思就是提取一系列词的词干。
我的思路是,首先将所有的按照词的长度分成一个一个的组(group),所有的组合并起来就是groups.
然后对for循环对每一个group进一步提取词干小组,子函数CreateGroup返回的是子结果(sub result),所有子结果的和加起来就是最后返回的结果

createGroup的原则是,首先计算出候选cand数组(candidate)所有词的词表,就一个26位的数组,数组中的数字是单词中字母出现的次数。以单词为关键词,这个字母的数组为值存到map里。
首先将cand中的第一个单词添加到list,并将这个list添加到subres。然后对比剩下的单词和subres中所有list的首个单词的词表,如果一样就加进那个list
createGroup返回的是长度相同单词里组成所有的词干组。


提交代码:

class Solution {
	public List<List<String>> groupAnagrams(String[] strs) {
		int i, j;
		List<List<String>> groups = new ArrayList<List<String>>();
		// strs with the same length will be stored in group,and
		// all group will be saved in groups
		for (i = 0; i < strs.length; i++) {
			for (j = 0; j < groups.size(); j++) {
				if (strs[i].length() == groups.get(j).get(0).length()) {
					groups.get(j).add(strs[i]);
					break;
				}
			}
			if (j == groups.size()) {
				List<String> group = new ArrayList<String>();
				group.add(strs[i]);
				groups.add(group);
			}
		}

		//print the groups
		//for (i = 0; i < groups.size(); i++) {
			//for (j = 0; j < groups.get(i).size(); j++)
				//System.out.print(groups.get(i).get(j) + "  ");
		//	System.out.println();
		//}
	
		List<List<String>> res=new ArrayList<List<String>>();
		for(i=0;i<groups.size();i++) {
			List<List<String>> subres=new ArrayList<List<String>>();
			subres=createGroup(groups.get(i));
			res.addAll(subres);
		}
	return res;
	}

	public List<List<String>> createGroup(List<String> cand) {
		List<List<String>> subres=new ArrayList<List<String>>();
		int i,j;
		
		//create HashMap
				Map<String,int[]> map=new HashMap<String,int[]>();
				for(i=0;i<cand.size();i++) {
					int cnt[]=new int[26];
					for(j=0;j<cand.get(i).length();j++) 
						cnt[(cand.get(i).charAt(j)-'a')]++;
					map.put(cand.get(i), cnt);
				}
				//show hashmap
			//for(i=0;i<cand.size();i++) {
					//for(j=0;j<26;j++)
						//System.out.print(map.get(cand.get(i))[j]);
				//System.out.println();
				//}
				
				//add the first word into the subres
				List<String> list=new ArrayList<String>();
				list.add(cand.get(0));
				subres.add(list);
				for(i=1;i<cand.size();i++) {
					list=new ArrayList<String>();

					//find duplicate
					for(j=0;j<subres.size();j++) {
						if(Arrays.equals(map.get(cand.get(i)), map.get(subres.get(j).get(0)))) {
						
						//if(map.get(cand.get(i))==map.get(subres.get(j).get(0))) {
							subres.get(j).add(cand.get(i));
							break;
							}
					}
					if(j==subres.size()) {
						list.add(cand.get(i));
						subres.add(list);
					}
				}
				return subres;
}
}

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/AXIMI/article/details/83861911
今日推荐