Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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;
}

 

posted on 2015-04-30 13:29  Tonix  阅读(469)  评论(0编辑  收藏  举报