[Leetcode] 336. Palindrome Pairs_Hard
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"]
这道题的思路就是把每个word和index存到diction里面, 然后针对每个word, for loop, 拆分为两部分, 如果前面部分是palindrome, 那么把后面部分的单词reverse, 如果reverse后的单词在diction里面, ans.append(d[back], index); 同理, 如果后面部分是palindrome, 把前面部分的单词reverse, 如果reverse后的单词在diction里面, ans.append(index, d[back]). 此时需要注意的是在后面check的时候就不要考虑整个单词reverse的情况, 因为前面单词reverse的时候已经考虑到了. 如果不明白的话就用set去去重, 最保险的做法.
参考Solution.
class Solution(object):
def palindromePairs(self, words):
"""
:type words: List[str]
:rtype: List[List[int]]
"""
def checkpal(w):
return w == w[::-1] # 反正O(n), 所以用最粗暴的方式 d, ans = {w:index for index, w in enumerate(words)},[]
for word, index in d.items():
l = len(word)
for i in range(l+1): # l+1 因为pref要到[:l]
pref = word[:i]
suf = word[i:]
if checkpal(pref):
back = suf[::-1]
if back != word and back in d:
ans.append([d[back], index]) if i != l and checkpal(suf): # delete the duplicates
back = pref[::-1]
if back != word and back in d:
ans.append([index, d[back]])
return ans
最新文章
- 安装angular-cli
- WPF自定义空心文字
- wordpress自动清理评论回收站
- sublime text2 解决中文乱码
- 20145210 《Java程序设计》第十周学习总结
- Stage3D学习笔记(四):正交矩阵
- 7.3.2 Using Backups for Recovery 使用备份用于恢复
- 为什么ajax 必须同源,same origin policy
- 项目管理之 SVN 管理软件 CornerStone for Mac
- 【GDOI2016模拟3.16】幂(容斥 + 模型复杂转化)
- yslow V2 准则详细讲解
- nginx rate limit
- sublime text3 key
- win命令行下载
- python 3.6.5 map() max() lambda匿名函数
- logistic回归梯度上升优化算法
- 通过汇编一个简单的C程序,分析汇编代码理解计算机是如何工作的
- cocos2d-js V3.0 V3.1使用DragonBones
- 【Eclipse】Ubuntu 下菜单栏失效了,怎么办?(已解决)
- HashMap 的工作原理及代码实现,什么时候用到红黑树
热门文章
- Elasticsearch学习之查询去重
- mybatis generator如何定制JavaTypeResolver,使smallint类型的数据库字段在po中的类型为Integer?
- 惠普hp服务器通过iLO接口远程安装操作系统
- 【CF671E】Organizing a Race 单调栈+线段树
- [SharePoint 2010] SharePoint 2010 部署、收回和删除解决方案----STSADM和PowerShell
- iOS取整
- Mecanim高级主题:Mecanim Blend Tree应用、Blend Tree 选项、复合Blend Tree
- jstack命令的使用
- Redis学习资料整理
- git--指定不上传的文件夹