题目地址
https://leetcode-cn.com/problems/group-anagrams/
题目描述
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Example 2:
Input: strs = [""]
Output: [[""]]
Example 3:
Input: strs = ["a"]
Output: [["a"]]
Constraints:
- 1 <= strs.length <= 104
- 0 <= strs[i].length <= 100
- strs[i] consists of lower-case English letters.
思路
也没用hash,就硬做,当个字符串题来做。
用个flag数组对应上lists,flag来记录lists里对应的list里存的是哪个排列的字符串。
题解
class Solution {
List<List<String>> lists = new ArrayList<List<String>>();
int cnt = 0;
public int[][] flag;
public List<List<String>> groupAnagrams(String[] strs) {
flag = new int[10000][27];
for(int i=0;i<strs.length;++i){
String str = strs[i];
boolean ok = false;
for(int j=0;j<cnt;++j)
if(match(j,str)){
lists.get(j).add(str);
ok = true;
}
if(!ok){//如果已有str的组合,添加,没有的话就添加上
for(int j=0;j<str.length();++j)
flag[cnt][str.charAt(j)-'a'] ++;
flag[cnt][26] = str.length();
List<String> list = new ArrayList<String>();
list.add(str);
lists.add(list);
cnt++;
}
}
return lists;
}
public boolean match(int i,String str){
if(flag[i][26]!=str.length()) return false;
int[] temp = new int[27];
for(int j=0;j<27;++j)
temp[j] = flag[i][j];
for(int j=0;j<str.length();++j){
temp[str.charAt(j)-'a']--;
if(temp[str.charAt(j)-'a']<0) return false;
}
return true;
}
}