Untitled

mail@pastecode.io avatar
unknown
c_cpp
2 months ago
613 B
1
Indexable
Never
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;
    }
};
Leave a Comment