题解 | #所有的回文子串II#
所有的回文子串II
https://www.nowcoder.com/practice/3373d8924d0e441987650194347d3c53
知识点:字符串,双指针
对于判断回文子串,可以通过双指针的思想,将i,j指针指向字符串两侧,若存在不相同字符,则判定为非回文串。我们通过两层遍历整个字符串的所有子串情况,找到所有的回文子串,题目要求按字典序排序,不能有重复子回文串,故我们采用TreeSet来存储结果,指定字典序升序的比较器,最终使用set.toArray(res)方法转换为数组。
Java题解如下
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return string字符串一维数组 */ public String[] partitionII (String s) { // write code here TreeSet<String> set = new TreeSet<>((o1, o2) -> o1.compareTo(o2)); for(int i = 0; i < s.length(); i++) { for(int j = i + 1; j < s.length(); j++) { if(check(s, i, j)) { set.add(s.substring(i, j + 1)); } } } String[] res = new String[set.size()]; set.toArray(res); return res; } private boolean check(String s, int i, int j) { while(i < j) { if(s.charAt(i) != s.charAt(j)) { return false; } i++; j--; } return true; } }