题解 | #所有的回文子串II#
所有的回文子串II
https://www.nowcoder.com/practice/3373d8924d0e441987650194347d3c53
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return string字符串一维数组
*/
public String[] partitionII (String s) {
// write code here
TreeSet<String> treeSet = new TreeSet<>(String::compareTo);
for (int i = 0; i < s.length(); i++) {
for (int j = i + 1; j < s.length(); j++) {
if (check(s, i, j)) {
treeSet.add(s.substring(i, j + 1));
}
}
}
String[] res = new String[treeSet.size()];
int i = 0;
for (String str : treeSet) {
res[i++] = str;
}
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;
}
}
知识点:
1.哈希表去重
2.字符串回文判断
3.字典序排序
解题思路分析:
1.利用TreeSet维护字典序,String::compareTo ->Lambda表达式
2.穷举O(N2)双重for判断回文情况,添加到集合中
3.增加for集合转数组,返回即可
编程语言:
Java
腾讯音乐娱乐集团公司福利 283人发布