标签:
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