今天本来是要练习“给定一个字符串 s
,找到 s
中最长的回文子串”这个算法题的,但一开始理解错了意思,没有真正了解到“回文子串”的定义,写了一道“字符串中最长首尾相同的子字符串”的代码。由于这个解答使用了新的思路:Map集合key唯一,同key的值(索引)互减求最大解得索引,具体代码如下:
public static void main(String[] args) {
String s = "abcda";
longestPalindrome(s);
}
public static String longestPalindrome(String s) {
if (s.isEmpty()) {
return s;
}
char[] chars = s.toCharArray();
int len = s.length();
Map<Character, Integer> map1 = new HashMap<>();
// 循环遍历正序索引存储map集合
for (int i = 0; i < len; i++) {
map1.put(chars[i], i);
}
Map<Character, Integer> map2 = new HashMap<>();
// 循环遍历倒序索引存储map集合
for (int i = len - 1; i >= 0; i--) {
map2.put(chars[i], i);
}
int temp = 0, lindex = 0, rindex = 0;
for (int i = 0; i < len; i++) {
if (temp < map1.get(chars[i]) - map2.get(chars[i])) {
rindex = map1.get(chars[i]);
lindex = map2.get(chars[i]);
temp = rindex - lindex;
}
}
return s.substring(lindex, rindex) + s.charAt(rindex);
}