zoukankan      html  css  js  c++  java
  • 336 Palindrome Pairs 回文对

    给定一组独特的单词, 找出在给定列表中不同 的索引对(i, j),使得关联的两个单词,例如:words[i] + words[j]形成回文。
    示例 1:
    给定 words = ["bat", "tab", "cat"]
    返回 [[0, 1], [1, 0]]
    回文是 ["battab", "tabbat"]
    示例 2:
    给定 words = ["abcd", "dcba", "lls", "s", "sssll"]
    返回 [[0, 1], [1, 0], [3, 2], [2, 4]]
    回文是 ["dcbaabcd", "abcddcba", "slls", "llssssll"]

    详见:https://leetcode.com/problems/palindrome-pairs/description/

    C++:

    class Solution {
    public:
        vector<vector<int>> palindromePairs(vector<string>& words) {
            vector<vector<int>> res;
            unordered_map<string, int> m;
            set<int> s;
            for (int i = 0; i < words.size(); ++i) 
            {
                m[words[i]] = i;
                s.insert(words[i].size());
            }
            for (int i = 0; i < words.size(); ++i) 
            {
                string t = words[i];
                int len = t.size();
                reverse(t.begin(), t.end());
                if (m.count(t) && m[t] != i)
                {
                    res.push_back({i, m[t]});
                }
                auto a = s.find(len);
                for (auto it = s.begin(); it != a; ++it) 
                {
                    int d = *it;
                    if (isValid(t, 0, len - d - 1) && m.count(t.substr(len - d))) 
                    {
                        res.push_back({i, m[t.substr(len - d)]});
                    }
                    if (isValid(t, d, len - 1) && m.count(t.substr(0, d)))
                    {
                        res.push_back({m[t.substr(0, d)], i});
                    }
                }
            }
            return res;
        }
        bool isValid(string t, int left, int right) 
        {
            while (left < right)
            {
                if (t[left++] != t[right--])
                {
                    return false;
                }
            }
            return true;
        }
    };
    

     参考:https://leetcode.com/problems/palindrome-pairs/description/

  • 相关阅读:
    EasyUI treegrid 加载checked
    html 文字垂直居中
    SQLSERVER 2008 查询数据字段名类型
    EasyUI TreeJson
    win7 网站发布备注
    LVS Nginx HAProxy 优缺点
    快速安装laravel和依赖
    Whoops, looks like something went wrong
    View.findViewById()和Activity.findViewById()区别
    ListView下拉刷新,上拉自动加载更多
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8835711.html
Copyright © 2011-2022 走看看