zoukankan      html  css  js  c++  java
  • Leetcode49. Group Anagrams字母异位词分组

    给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

    示例:

    输入: ["eat", "tea", "tan", "ate", "nat", "bat"], 输出: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ]

    说明:

    • 所有输入均为小写字母。
    • 不考虑答案输出的顺序。

    暴力:

    因为只有小写字母,所以检查每个字符串中各个字符出现次数的数组只需把大小设置为26

    class Solution {
    public:
        vector<vector<string> > groupAnagrams(vector<string>& strs)
        {
            int len = strs.size();
            vector<vector<string> > res;
            vector<vector<int> > check(len, vector<int>(26, 0));
            vector<bool> visit(len, false);
            for(int i = 0; i < len; i++)
            {
                for(int j = 0; j < strs[i].size(); j++)
                {
                    check[i][strs[i][j] - 'a']++;
                }
            }
            for(int i = 0; i < len; i++)
            {
                if(visit[i] == true)
                    continue;
                vector<string> temp;
                temp.push_back(strs[i]);
                for(int j = i + 1; j < len; j++)
                {
                    if(visit[i] == true)
                        continue;
                    if(strs[i].size() != strs[j].size())
                        continue;
                    int flag = true;
                    for(int k = 0; k < 26; k++)
                    {
                        if(check[i][k] != check[j][k])
                        {
                            flag = false;
                            break;
                        }
                    }
                    if(flag)
                    {
                        temp.push_back(strs[j]);
                        visit[j] = true;
                    }
                }
                res.push_back(temp);
            }
            return res;
        }
    };
  • 相关阅读:
    学习进度条7
    2016年秋季个人阅读计划
    WampServer中MySQL中文乱码解决
    LINK : fatal error LNK1104: 无法打开文件“LIBCD.lib”
    人月神话阅读笔记03
    人月神话阅读笔记02
    个人总结
    人月神话阅读笔记01
    学习进度条15
    学习进度14
  • 原文地址:https://www.cnblogs.com/lMonster81/p/10433870.html
Copyright © 2011-2022 走看看