Untitled

 avatar
unknown
c_cpp
a year ago
613 B
4
Indexable
class Solution {
public:
    using ll = long long;
    ll countPrefixSuffixPairs(vector<string>& words) {
        unordered_map<string, int> prefixSuffixCount;
        ll ans = 0;
        // Count all words
        for (auto& word : words) {
            int n = word.size();
            for (int i = 1; i <= n; i++) {
                string prefix = word.substr(0, i);
                string suffix = word.substr(word.size() - i);
                if(prefix == suffix)
                    ans += prefixSuffixCount[prefix];
            }
            prefixSuffixCount[word]++;
        }
        return ans;
    }
};
Editor is loading...
Leave a Comment