作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/palindrome-pairs/description/

题目描述

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:

Input: ["abcd","dcba","lls","s","sssll"]
Output: [[0,1],[1,0],[3,2],[2,4]]
Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"]

Example 2:

Input: ["bat","tab","cat"]
Output: [[0,1],[1,0]]
Explanation: The palindromes are ["battab","tabbat"]

题目大意

如果从input进来的字符串中选取两个拼接在一起能构成回文字符串,那么就把这两个的索引加入到结果中。返回所有的索引列表。

解题方法

HashTable

这个题暴力求解会超时,优秀的解法还真不是容易想出来。不愧是Hard题啊,这个也是我做的第600个题。我就照搬大神的解法了[LeetCode]Palindrome Pairs

O(k * n ^2)解法 其中k为单词个数,n为单词的长度:

利用字典wmap保存单词 -> 下标的键值对

遍历单词列表words,记当前单词为word,下标为idx:

1). 若当前单词word本身为回文,且words中存在空串,则将空串下标bidx与idx加入答案

2). 若当前单词的逆序串在words中,则将逆序串下标ridx与idx加入答案

3). 将当前单词word拆分为左右两半left,right。

     3.1) 若left为回文,并且right的逆序串在words中,则将right的逆序串下标rridx与idx加入答案

     3.2) 若right为回文,并且left的逆序串在words中,则将left的逆序串下标idx与rlidx加入答案

时间复杂度是O(k * n ^2),空间复杂度是O(kN).

class Solution(object):
def palindromePairs(self, words):
"""
:type words: List[str]
:rtype: List[List[int]]
"""
wmap = {w : i for i, w in enumerate(words)} def isPalindrome(word):
_len = len(word)
for x in range(_len / 2):
if word[x] != word[_len - x - 1]:
return False
return True res = set()
for idx, word in enumerate(words):
if word and isPalindrome(word) and "" in wmap:
nidx = wmap[""]
res.add((idx, nidx))
res.add((nidx, idx)) rword = word[::-1]
if word and rword in wmap:
nidx = wmap[rword]
if idx != nidx:
res.add((idx, nidx))
res.add((nidx, idx)) for x in range(1, len(word)):
left, right = word[:x], word[x:]
rleft, rright = left[::-1], right[::-1]
if isPalindrome(left) and rright in wmap:
res.add((wmap[rright], idx))
if isPalindrome(right) and rleft in wmap:
res.add((idx, wmap[rleft]))
return list(res)

相似题目

参考资料

http://bookshadow.com/weblog/2016/03/10/leetcode-palindrome-pairs/

日期

2018 年 11 月 1 日 —— 小光棍节

【LeetCode】336. Palindrome Pairs 解题报告(Python)的更多相关文章

  1. LeetCode 336. Palindrome Pairs

    原题链接在这里:https://leetcode.com/problems/palindrome-pairs/ 题目: Given a list of unique words, find all p ...

  2. leetcode@ [336] Palindrome Pairs (HashMap)

    https://leetcode.com/problems/palindrome-pairs/ Given a list of unique words. Find all pairs of dist ...

  3. 【LeetCode】Palindrome Partitioning 解题报告

    [题目] Given a string s, partition s such that every substring of the partition is a palindrome. Retur ...

  4. 【LeetCode】120. Triangle 解题报告(Python)

    [LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...

  5. LeetCode 1 Two Sum 解题报告

    LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...

  6. 【LeetCode】Permutations II 解题报告

    [题目] Given a collection of numbers that might contain duplicates, return all possible unique permuta ...

  7. 【LeetCode】Island Perimeter 解题报告

    [LeetCode]Island Perimeter 解题报告 [LeetCode] https://leetcode.com/problems/island-perimeter/ Total Acc ...

  8. 【LeetCode】01 Matrix 解题报告

    [LeetCode]01 Matrix 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/01-matrix/#/descripti ...

  9. 【LeetCode】Largest Number 解题报告

    [LeetCode]Largest Number 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/largest-number/# ...

随机推荐

  1. 【Python小试】统计一条核酸序列中频数非0或为2的双核苷酸

    概念 双核苷酸由任意2个碱基组成 测试1 dna = "AATGATGAACGAC" #一一列举 dinucleotides = ['AA','AT','AG','AC', 'TA ...

  2. Python三元表达式,列表推导式,字典生成式

    目录 1. 三元表达式 2. 列表推导式 3. 字典生成式 3.1 字典生成式 3.2 zip()方法 1. 三元表达式 """ 条件成立时的返回值 if 条件 else ...

  3. 微信小程序调试bug-日程计划类

    首先嘤嘤嘤一下,破bug,改了我一天,摔(′д` )-彡-彡 写的个微信小程序 逻辑如下,正常的功能是,我可以新建,修改,查询(按筛选条件),删除某个日程信息,后面贴个页面,我的bug出现就很搞笑了, ...

  4. js获取中国省市区,省市筛选、省市、省市筛选联动。【C#】【js】

    <style type="text/css"> .labelhide { -webkit-box-shadow: 0px 1px 0px 0px #f3f3f3 !im ...

  5. opencv学习(三)——绘图功能

    绘图功能 我们将学习以下函数:cv.line(),cv.circle(),cv.rectangle(),cv.ellipse(),cv.putText()等. 在这些功能中,有一些相同的参数: img ...

  6. 技术管理进阶——Leader的模型、手段及思维

    这里可以添加关注交流一下嘛-- 本文更多的是个人认知,有不足请批评. ​Case 在之前一次年底考评的时候,有一位leader将一个案例同时用到了自己和下属身上,老板发出了责问: 这个项目到底你是负责 ...

  7. acquaint

    Interpersonal relationships are dynamic systems that change continuously during their existence. Lik ...

  8. Java 性能优化的 50 个细节

    在JAVA程序中,性能问题的大部分原因并不在于JAVA语言,而是程序本身.养成良好的编码习惯非常重要,能够显著地提升程序性能. #尽量在合适的场合使用单例 使用单例可以减轻加载的负担,缩短加载的时间, ...

  9. Copy constructor vs assignment operator in C++

    Difficulty Level: Rookie Consider the following C++ program. 1 #include<iostream> 2 #include&l ...

  10. javascript将平行的拥有上下级关系的数据转换成树形结构

    转换函数 var Littlehow = {}; /** * littlehow 2019-05-15 * 平行数据树形转换器 * @type {{format: tree.format, sort: ...