【马拉车算法/动态规划】最长回文字串
最长回文字串
- 1.问题描述
- 2.中心扩展法(O(N^2))
- 3.动态规划
- 4.Manacher(马拉车算法)
1.问题描述
常用有3种算法:中心扩展法、动态规划和Manacher算法
2.中心扩展法(O(N^2))
解释:
从中心向外扩展。
分为两种情况:第一种当回文串长度为奇数的情况;第二种当回文串长度为偶数的情况。
左右同时向外扩展,当左右不相同时停止扩展,记录最长回文串长度及起始位置。
public String longestPalindrome(String str) {if (Objects.isNull(str) || str.isEmpty()) {return "";}int maxStart = 0;int maxLength = 1;for (int i = 0; i < str.length(); i++) {for (int k = 0; k < 2; ++k) {int leftIndex = i - k; // k = 0表示偶数长度,k = 1表示奇数长度int rightIndex = i + 1;while (leftIndex >= 0&& rightIndex < str.length()&& str.charAt(leftIndex) == str.charAt(rightIndex)) {leftIndex--;rightIndex++;}if (maxLength < rightIndex - leftIndex - 1) { // 当前length = (rightIndex - 1) - (leftIndex + 1) + 1maxLength = rightIndex - leftIndex - 1;maxStart = leftIndex + 1;}}}return str.substring(maxStart, maxStart + maxLength);}