LeetCode T49 Group Anagrams

题目地址

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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值