题解 | #最长回文子串#
最长回文子串
https://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
private static Map<Character, List<Integer>> cIndexListMap = new HashMap<>();
private static String s = "";
private static int start = 0;
private static int end = 0;
private static String max = "";
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNext()) { // 注意 while 处理多个 case
s = in.next();
}
initMap();
int s = cIndexListMap.size();
result();
System.out.print(max.length());
}
private static void initMap() {
int len = s.length();
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
boolean b = cIndexListMap.containsKey(c);
if(b){
cIndexListMap.get(c).add(i);
} else {
List<Integer> list =new LinkedList<>();
list.add(i);
cIndexListMap.put(c, list);
}
}
}
private static void result() {
cIndexListMap.forEach((k, v) -> {
int size = v.size();
for (int i = 0; i < size - 1; i++) {
start = v.get(i);
for(int j=i+1;j<size;j++){
end = v.get(j);
check(start, end);
}
}
});
}
private static void check(int start1, int end1) {
char c = s.charAt(start1);
char c1 = s.charAt(end1);
if (c == c1) {
if (start1 + 1 == end1 - 1) {
if (end - start + 1 > max.length()) {
max = s.substring(start, end + 1);
}
return;
} else if (end1 - start1 == 1) {
if (end - start + 1 > max.length()) {
max = s.substring(start, end + 1);
}
return;
}
check(start1 + 1, end1 - 1);
}
}
}
以前二级考过的题,以前没做好,现在做出来感觉挺好。
雪域灰灰刷题笔记 文章被收录于专栏
雪域灰灰刷题笔记


