题解 | #所有的回文子串II# java
所有的回文子串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 List<String> result = new ArrayList<>(); if (s.isEmpty()) { return result.toArray(new String[0]); } for (int i = 0; i < s.length(); i++) { expandAroundCenter(s, i, i, result); expandAroundCenter(s, i, i + 1, result); } Set<String> uniqueSet = new HashSet<>(result); result.clear(); result.addAll(uniqueSet); result.sort(null); return result.toArray(new String[0]); } private void expandAroundCenter(String s, int left, int right, List<String> result) { while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { if (right - left + 1 > 1) { // Exclude single character substrings result.add(s.substring(left, right + 1)); } left--; right++; } } }
编程语言是Java。
这道题考察了字符串操作和回文子串的查找。
代码的文字解释:
partitionII
方法实现了根据给定字符串s
进行回文子串分割的功能。- 对于每个字符或相邻两个字符作为中心,向左右扩展来找到回文子串。
- 找到的回文子串添加到结果列表中。
- 对结果进行字典序排序,并去除重复的结果。
- 最后将结果转换为数组格式返回。