最长回文子串

题目描述:给你一个字符串 s,找到 s 中最长的回文子串。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-palindromic-substring/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:暴力破解法

遍历所有可能的子串,然后判断子串是否是回文子串,如果是,判断是否超过当前最长的长度,遍历完成即可得到最长的回文子串。 这是我第一个想到的方法, 尴尬的是leetcode上提交之后超出时间限制了,此方法不可取。

解法二:动态规划

动态规划效率更高,待完成。

  1. public class Solution {
  2. /**
  3. * 解法一:暴力破解法
  4. *
  5. * @param s
  6. * @return
  7. */
  8. public static String longestPalindrome(String s) {
  9. if (s == null || s.length() < 2) {
  10. return s;
  11. }
  12. String result = String.valueOf(s.charAt(0));
  13. int max = 1;
  14. StringBuilder sb;
  15. for (int i = 0; i < s.length() - 1; i++) {
  16. sb = new StringBuilder(String.valueOf(s.charAt(i)));
  17. for (int j = i + 1; j < s.length(); j++) {
  18. sb.append(s.charAt(j));
  19. if (checkPalindrome(sb.toString())) {
  20. if (sb.length() > max) {
  21. result = sb.toString();
  22. max = sb.length();
  23. }
  24. }
  25. }
  26. }
  27. return result;
  28. }
  29. /**
  30. * 解法二:动态规划
  31. *
  32. * @param s
  33. * @return
  34. */
  35. public static String longestPalindrome2(String s) {
  36. // TODO: 2021/6/7 待完成
  37. return null;
  38. }
  39. public static boolean checkPalindrome(String str) {
  40. if (str == null || str.length() == 1) {
  41. return true;
  42. }
  43. if (str.length() == 2 && str.charAt(0) == str.charAt(1)) {
  44. return true;
  45. }
  46. int count = str.length();
  47. for (int i = 0; i < count; i++) {
  48. if (str.charAt(i) != str.charAt(count - i - 1)) {
  49. return false;
  50. }
  51. }
  52. return true;
  53. }
  54. public static void main(String[] args) {
  55. // 超时的例子 后面还有很多很多个d
  56. System.out.println(longestPalindrome("dddddddd..."));
  57. }
  58. }