zoukankan      html  css  js  c++  java
  • 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 {
    private:
        bool isPalindrome(string s) {
            int left = 0;
            int right = s.length() - 1;
    
            while (left < right) {
                if (s[left++] != s[right--])
                    return false;
            }
            return true;
        }
    public:
        vector<vector<int>> palindromePairs(vector<string>& words) {
            vector<vector<int>> ret;
            unordered_map<string, int> dict;
            int size = words.size();
            for (int i = 0; i < size; i++) {
                string key = words[i];
                reverse(key.begin(), key.end());
                dict[key] = i;
            }
    
            if (dict.find("") != dict.end()) {
                for (int i = 0; i < size; i++) {
                    if (i == dict[""])
                        continue;
                    if (isPalindrome(words[i]))
                        ret.push_back( { dict[""], i });
                }
            }
    
            for (int i = 0; i < size; i++) {
                for (int j = 0; j < words[i].size(); j++) {
                    string left = words[i].substr(0, j);
                    string right = words[i].substr(j, words[i].size() - j);
    
                    if (dict.find(left) != dict.end() && isPalindrome(right)
                            && dict[left] != i) {
                        ret.push_back( { i, dict[left] });
                    }
                    if (dict.find(right) != dict.end() && isPalindrome(left)
                            && dict[right] != i) {
                        ret.push_back( { dict[right], i });
                    }
                }
            }
            return ret;
        }
    };
  • 相关阅读:
    linux编程 给线程起名字
    c语言的__packed__
    LINUX 命令行编辑快捷键
    linux关于bashrc与profile的区别(转)
    linux查看和修改PATH环境变量的方法
    linux 线程 pthread_create 源码 剖析
    你真的了解【HashMap】么?-一
    Oracle 基础概念
    Java数据库连接池
    JVM内存模型与垃圾回收
  • 原文地址:https://www.cnblogs.com/wxquare/p/5864088.html
Copyright © 2011-2022 走看看