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;
        }
    };
  • 相关阅读:
    System.Web.HtppRuntime.cs
    Code:Tree
    Code-Helper-Web:CacheHelper.cs
    Code-Helper-Web:CookieHelper.cs
    ORACLE数据库常用查询二
    涂抹Oracle笔记2:数据库的连接-启动-关闭
    windows下常用的操作命令及dos命令
    涂抹Oracle笔记1-创建数据库及配置监听程序
    表空间满处理方法
    SQL内连接-外连接join,left join,right join,full join
  • 原文地址:https://www.cnblogs.com/wxquare/p/5864088.html
Copyright © 2011-2022 走看看