zoukankan      html  css  js  c++  java
  • HackerRank

    Please note input constraints. String length will not exceed 100, which means, we can use relatively naive representationcalculation 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;
    }
  • 相关阅读:
    20140830 函数 递归
    函数 20140829
    结构体20140827
    20140826 集合
    20140822数组,应用举例
    140821 字符串,数字,日期及应用举例
    20140819 例子
    HTML基础
    登陆远程服务器
    索引 视图 游标
  • 原文地址:https://www.cnblogs.com/tonix/p/4468668.html
Copyright © 2011-2022 走看看