标签:
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); }
标签:
原文地址:http://www.cnblogs.com/lcchuguo/p/5379066.html