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

HackerRank - Sherlock and Anagram

时间:2015-04-30 13:56:35      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:

Please note input constraints. String length will not exceed 100, which means, we can use relatively naive representation\calculation for anagrams: sorting.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;

int calc(string &str)
{
    int ret = 0;
    size_t len = str.length();

    unordered_map<string, int> rec;
    for (size_t ilen = 1; ilen < len; ilen++)
    {
        for (size_t i = 0; i <= len - ilen; i++)
        {
            string curr = str.substr(i, ilen);
            std::sort(curr.begin(), curr.end());
            rec[curr]++;
        }
        
        //
        for (auto &r : rec)
            if (r.second > 1)
                ret += r.second * (r.second - 1) / 2;
        rec.clear();
    }
    return ret;
}

int main() 
{
    int n; cin >> n;
    while (n--)
    {
        char buf[102] = { 0 };
        scanf("%s", buf);

        string str(buf);
        int ret = calc(str);
        cout << ret << endl;
    }
    return 0;
}

 

HackerRank - Sherlock and Anagram

标签:

原文地址:http://www.cnblogs.com/tonix/p/4468668.html

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