Java 题解 | #所有的回文子串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
int n = s.length();
TreeSet<String> res = new TreeSet<>();
for (int i = 0; i < n; i ++) {
for (int j = i + 1; j <= n; j ++) {
if (check(s, i, j - 1)) {
res.add(s.substring(i, j));
}
}
}
return res.toArray(new String[0]);
}
private boolean check(String s, int l, int r) {
if (r - l < 1) {
return false;
}
for (int i = l, j = r; i < j; i ++, j --) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
}
return true;
}
}
Java代码。
该题考察的知识点是字符串处理和判断回文。
代码的文字解释如下:
partitionII方法接受一个字符串s作为输入,返回一个字符串数组。- 创建一个
TreeSet集合res来存储结果,确保结果按照字典序升序排序。 - 使用两层循环遍历字符串
s的所有可能子串,外层循环变量i表示起始位置,内层循环变量j表示结束位置。 - 对于每个子串,调用
check方法来判断是否为回文串。如果是回文串,则将其加入到res中。 - 将
res转换为字符串数组并返回。