leetcode 336. Palindrome Pairs

来源:互联网 发布:大学生使用网络情况 编辑:程序博客网 时间:2024/06/07 10:29

336. Palindrome Pairs

Given a list of unique words, find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome.

Example 1:
Given words = ["bat", "tab", "cat"]
Return [[0, 1], [1, 0]]
The palindromes are ["battab", "tabbat"]

Example 2:
Given words = ["abcd", "dcba", "lls", "s", "sssll"]
Return [[0, 1], [1, 0], [3, 2], [2, 4]]
The palindromes are ["dcbaabcd", "abcddcba", "slls", "llssssll"]


暴力解题会超时。

把出现过的单词的长度挨个拿出来,搜索当前单词的除去该长度的部分。如果存在,那就能构成回文。


class Solution {public:    vector<vector<int>> palindromePairs(vector<string>& words)     {        vector<vector<int>> ret;        map<string, int> mp;    //存所有单词,方便后面搜索        set<int> st;            //存单词出现过的长度        for (int i = 0; i < words.size(); i++)        {            mp[words[i]] = i;            st.insert(words[i].size());        }                for (int i = 0; i < words.size(); i++)        {            string s = words[i];            int len = s.size();            reverse(s.begin(), s.end());            if (mp.find(s) != mp.end() && mp[s] != i) //还不能是本身            {                ret.push_back({i, mp[s]});            }            for (auto it = st.begin(); it != st.end(), *it < len; it++)            {                if (ispalind(s.substr(0, len - *it)) && mp.find(s.substr(len - *it)) != mp.end())                {                    ret.push_back({i, mp[s.substr(len - *it)]});                }                if (ispalind(s.substr(*it)) && mp.find(s.substr(0, *it)) != mp.end())                {                    ret.push_back({mp[s.substr(0, *it)], i});                 }            }        }        return ret;    }        bool ispalind(string s1)    {        string s2 = s1;        reverse(s2.begin(), s2.end());        return s1 == s2;    }};


原创粉丝点击