336. Palindrome Pairs
来源:互联网 发布:网线端口坏了是怎样的 编辑:程序博客网 时间:2024/06/03 19:33
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 List<List<Integer>> palindromePairs(String[] words) { Map<String, Integer> map = new HashMap<>(); for (int i = 0; i < words.length; i++) { map.put(words[i], i); } List<List<Integer>> indices = new ArrayList<>(); for (int i = 0; i < words.length; i++) { if (words[i].length() == 0) { //如果是空串,那么可以与任何回文字符串结合 for (Map.Entry<String, Integer> entry : map.entrySet()) { if (isPalindrome(entry.getKey())) { addAll(indices, i, entry.getValue()); } } } for (int j = 0; j < words[i].length(); j++) { //不是空串的话,分别切割每一个字符,查看前后是不是回文 String front = words[i].substring(0, j);//如果有回文的话,查一下剩下的在不在map里面 String back = words[i].substring(j, words[i].length()); String rfront = reverse(front); String rback = reverse(back); if (isPalindrome(front) && map.containsKey(rback)) { addAll(indices, map.get(rback), i); } if (isPalindrome(back) && map.containsKey(rfront)) { addAll(indices, i, map.get(rfront)); } } } return indices; } private void addAll(List<List<Integer>> indices, int a, int b) { if (a == b) { return; } List<Integer> list = new ArrayList<>(); list.add(a); list.add(b); indices.add(list); } private String reverse(String word) { return new StringBuilder(word).reverse().toString(); } private boolean isPalindrome(String word) { for (int i = 0, j = word.length() - 1; i < j; i++, j--) { if (word.charAt(i) != word.charAt(j)) { return false; } } return true; }
阅读全文
0 0
- LeetCode 336. Palindrome Pairs
- LeetCode 336. Palindrome Pairs
- leetcode 336. Palindrome Pairs
- LeetCode 336. Palindrome Pairs
- leetcode.336. Palindrome Pairs
- 336. Palindrome Pairs
- 336. Palindrome Pairs
- [leetcode] 336. Palindrome Pairs
- 336. Palindrome Pairs
- LeetCode-336.Palindrome Pairs
- LeetCode 336. Palindrome Pairs
- 336. Palindrome Pairs
- 336. Palindrome Pairs
- [LeetCode]336. Palindrome Pairs
- 336. Palindrome Pairs
- 336. Palindrome Pairs
- leetcode 336. Palindrome Pairs
- 336. Palindrome Pairs
- Tomcat学习之Connector
- Mysql 下载与安装问题一:无法启动此程序,因为计算机丢失MSVCR120.dll
- Windows平台上Docker安装与使用
- java8新特性lambda表达式
- [BZOJ4319][cerc2008]Suffix reconstruction(贪心)
- 336. Palindrome Pairs
- windows系统下iis注册
- [BZOJ4402]Claris的剑(组合数学)
- 数字统计
- 字符统计
- 51Nod--1002 数塔取数问题
- 28岁才开始学习PHP,并不晚!
- 日常训练 20170531 数字
- 298. Binary Tree Longest Consecutive Sequence