[LeetCode] Palindrome Pairs
来源:互联网 发布:山东双轨直销软件 编辑:程序博客网 时间:2024/06/04 23:23
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"]
代码:
public class Solution {//这里的去重一定要注意 重点在于对一个字符串整体反转找对应的串的时候,这时候只找一边即可,如果找两边,会造成重复,重点看两个for循环下标 public List<List<Integer>> palindromePairs(String[] words) { List<List<Integer>> re=new ArrayList<List<Integer>>(); if(words.length==0) return re; HashMap<String,Integer> map=new HashMap<String,Integer>(); for(int i=0;i<words.length;i++) map.put(words[i],i); for(int i=0;i<words.length;i++){ String str=words[i]; for(int k=0;k<=str.length();k++){ String s1=str.substring(0,k); String s11=str.substring(k); String s2=reverse(s1); if(map.containsKey(s2)&&map.get(s2)!=i&&isPar(s11)){ List<Integer> one=new ArrayList<Integer>(); one.add(i);one.add(map.get(s2)); re.add(one); } } for(int k=1;k<=str.length();k++){ String s1=str.substring(k); String s11=str.substring(0,k); String s2=reverse(s1); if(map.containsKey(s2)&&isPar(s11)){ List<Integer> one=new ArrayList<Integer>(); one.add(map.get(s2));one.add(i); re.add(one); } } } return re; } public String reverse(String str){ StringBuffer sb=new StringBuffer(); for(int i=0;i<str.length();i++){ sb.append(str.charAt(str.length()-1-i)); } return sb.toString(); } public boolean isPar(String str){ for(int i=0;i<str.length()/2;i++){ if(str.charAt(i)!=str.charAt(str.length()-1-i)) return false; } return true; }}
阅读全文
1 0
- [LeetCode]Palindrome Pairs
- LeetCode: Palindrome Pairs
- LeetCode 336. Palindrome Pairs
- LeetCode 336. Palindrome Pairs
- LeetCode Palindrome Pairs
- leetcode 336. Palindrome Pairs
- 【leetcode】Palindrome Pairs
- [LeetCode] Palindrome Pairs
- LeetCode 336. Palindrome Pairs
- LeetCode No336. Palindrome Pairs
- leetcode.336. Palindrome Pairs
- Leetcode Palindrome Pairs
- [leetcode] 336. Palindrome Pairs
- 【Leetcode】Palindrome Pairs
- LeetCode-336.Palindrome Pairs
- LeetCode 336. Palindrome Pairs
- Leetcode Palindrome Pairs
- [LeetCode]336. Palindrome Pairs
- request对象
- LDD3 linux设备驱动程序学习之lddbus
- 矩形面积并、矩形面积交、矩形周长并(线段树、扫描线总结)
- Widget 桌面小控件
- SQL truncate 、delete和drop的异同
- [LeetCode] Palindrome Pairs
- MyBatis动态查询(where trim set)
- HTML DOM之属性的各种操作方法
- 【MongoDB】mongo时间问题
- JavaScript 跨域访问的问题和解决过程
- calico iptables详解
- 小明的调查作业
- Linux中安装numpy,scipy,matplotib,opencv等函数库
- HTTP 2.0 Client & HTTP 2.0 Server & HTTP 2.0 Proxy