标签:java leetcode string 字符串 回文
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
以时间换空间的方法。 子串[i, j] 是回文串的要求是: 字符(i) == 字符(j) 且子串[i + 1, j - 1]也是回文串。每次将结果保存。public String longestPalindrome(String s) { if (s == null) { return null; } if (s.length() <= 1) { return s; } int len = s.length(); boolean[][] status = new boolean[len][len]; for (int interval = 0; interval < len; interval++) { for (int i = 0; i < len - interval; i++) { int j = i + interval; if (i == j) { status[i][j] = true; } else if (s.charAt(i) == s.charAt(j)) { if (i + 1 < j - 1) { if (status[i + 1][j - 1] == true) { status[i][j] = true; } } else { status[i][j] = true; } } } } int left = 0; int right = 0; for (int interval = 0; interval < len; interval++) { for (int i = 0; i < len - interval; i++) { int j = i + interval; if (status[i][j] == true) { left = i; right = j; break; } } } return s.substring(left, right + 1); }
Longest Palindromic Substring,布布扣,bubuko.com
标签:java leetcode string 字符串 回文
原文地址:http://blog.csdn.net/u010378705/article/details/33330927