import java.util.HashMap;
import java.util.Map;
/**
* @ClassName longestPalidrome
* @Description 字符串中最长首尾相同的子字符串
* @Author zhaolingyu
* @Date 2022/9/9 18:26
* @Version 1.0
*/
public class longestPalidrome {
public String longest(String s){
if(s.isEmpty()) return s;
char[] chars = s.toCharArray();
Map<Character,Integer> map1 = new HashMap<>();
for(int i=0;i<chars.length;i++){
map1.put(chars[i],i);
}
Map<Character,Integer> map2 = new HashMap<>();
for(int i=chars.length-1;i>=0;i--){
map2.put(chars[i],i);
}
int temp = 0,lindex=0,rindex=0;
for(int i=0;i<chars.length;i++){
if(map1.get(chars[i])-map2.get(chars[i])>temp){
lindex = map2.get(chars[i]);
rindex = map1.get(chars[i]);
temp = rindex - lindex;
}
}
return s.substring(lindex,rindex)+s.charAt(rindex);
}
public static void main(String[] args) {
longestPalidrome l = new longestPalidrome();
System.out.println(l.longest("ababab"));
}
}