码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Anagrams

时间:2014-07-27 21:53:19      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

struct mystat {
    int idx;
    int cnt[26];
    mystat(int id = 0) {idx = id;}
};

bool cmp(const mystat &a, const mystat &b) {
    for (int i=0; i<26; i++) {
        if (a.cnt[i] < b.cnt[i]) {
            return true;
        } else if (a.cnt[i] > b.cnt[i]) {
            break;
        } else {
            continue;
        }
    }
    return false;
}

bool same(const mystat &a, const mystat &b) {
    for (int i=0; i<26; i++) {
        if (a.cnt[i] != b.cnt[i]) return false;
    }
    return true;
}

class Solution {
public:
    vector<string> anagrams(vector<string> &strs) {
        vector<string> res;
        vector<mystat> stats;

        int len = strs.size();

        for (int i=0; i<len; i++) {
            stats.push_back(mystat(i));

            for (int j=strs[i].size() - 1; j>=0; j--) {
                stats.back().cnt[strs[i][j] - a]++;
            }
        }
        
        sort(stats.begin(), stats.end(), cmp);

        int si = 0;

        while (si < len ) {
            int i = si + 1;
            for (; i<len; i++) {
                if (same(stats[si], stats[i])) {
                    res.push_back(strs[stats[i].idx]);
                } else {
                    break;
                }
            }
            if (si + 1 < i) {
                res.push_back(strs[stats[si].idx]);
            }
            si = i;
        }
        return res;
    }
    
};

虽然做出来了,不过写那么长,时间又是150ms+肯定还有什么巧妙的方法。

LeetCode Anagrams

标签:

原文地址:http://www.cnblogs.com/lailailai/p/3871245.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!