题目描述

解题思路

双指针

和647双指针的方法一致,都是根据0和1进行扩散来判断。最终返回最长的子串,和516有区别,516是子序列。

  1. // 从中间向左右扩散的双指针解法
  2. public String longestPalindrome(String s) {
  3. String res = "";
  4. for (int i = 0; i < s.length(); i++) {
  5. String s1 = palindrome(s, i, i);
  6. String s2 = palindrome(s, i, i + 1);
  7. res = res.length() > s1.length() ? res : s1;
  8. res = res.length() > s2.length() ? res : s2;
  9. }
  10. return res;
  11. }
  12. // 判断字符串区间开始是否是回文子串
  13. public String palindrome(String s, int l, int r) {
  14. while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
  15. l--;
  16. r++;
  17. }
  18. return s.substring(l + 1, r);
  19. }

dp

和647相差不大,就是求最大的回文子串。

  1. /**
  2. * 回文子串类型题
  3. *
  4. * @param s
  5. * @return
  6. */
  7. public String longestPalindrome(String s) {
  8. if (s.length() == 1) {
  9. return s;
  10. }
  11. boolean[][] dp = new boolean[s.length()][s.length()];
  12. for (int i = 0; i < s.length(); i++) {
  13. dp[i][0] = false;
  14. dp[0][i] = false;
  15. }
  16. int result = 0;
  17. String str = String.valueOf(s.charAt(0));
  18. for (int i = s.length() - 1; i >= 0; i--) {
  19. for (int j = i; j < s.length(); j++) {
  20. if (s.charAt(i) == s.charAt(j)) {
  21. if (j - i <= 1) {
  22. dp[i][j] = true;
  23. if (j - i > result) {
  24. result = j - i;
  25. str = s.substring(i, j + 1);
  26. }
  27. } else if (dp[i + 1][j - 1]) {
  28. dp[i][j] = true;
  29. if (j - i > result) {
  30. result = j - i;
  31. str = s.substring(i, j + 1);
  32. }
  33. }
  34. }
  35. }
  36. }
  37. return str;
  38. }