I. Question
1. Question Review
2. Analysis
A string is given, and a character is added to the front of the string to make it a background. After the minimum characters are added, the background is formed.
Ii. Answers
1. Ideas:
① To handle the problem of odd and even number of characters in the return, insert '#' between each character in string S and put each character into a list.
② Subscript indexes are defined from 1 to mid, and left = index-1 and Right = index + 1 are defined;
Compare whether the elements indicated by left and right are equal. If they are not equal, index moves backward. If they are equal, left and right move backward until left <0, that is, the index-centered string is input. Index of the largest character in the retrieval Center
③ Insert the trailing molecular string of s that is not contained in the string with the largest index obtained by ② into a stringbuilder in reverse order, insert s into this stringbuilder, and return.
1 public String shortestPalindrome(String s) { 2 3 List<Character> list = new ArrayList<>(); 4 list.add(‘#‘); 5 for(char c: s.toCharArray()) { 6 list.add(c); 7 list.add(‘#‘); 8 } 9 10 int len = list.size();11 int mid = (len - 1) / 2;12 int i = 1;13 int max = 0;14 while(i <= mid) {15 int left = i - 1;16 int right = i + 1;17 while(left >= 0 && right <= len - 1) {18 if(list.get(left) != list.get(right))19 break;20 left--;21 right++;22 }23 if(left <= 0)24 max = i;25 i++;26 }27 max = max * 2 + 1;28 StringBuilder sb = new StringBuilder();29 for (int j = len - 1; j >= max; j--) {30 if(list.get(j) != ‘#‘)31 sb.append(list.get(j));32 }33 sb = sb.append(s);34 return sb.toString();35 }
214. Shortest palindrome