题目:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
题目翻译:
很经典的题目,求最长回文字符串
解题思路:
我目前只会使用动态规划的方式进行求解。构建flagslen表格,其中flagsi表示字符串子串(i..j)是否为回文,如果flagi为回文,且flagsi+1,也就是内部子串也为回文的情况下,则认为一定是回文。
代码:
fn longest_palindrome(s: String) -> String {
let size = s.len();
if size == 0 {
return String::from("");
}
let mut flags = vec![vec![false; size]; size];
let mut start = 0;
let mut max = 1;
let b = s.as_bytes();
for i in (0..size) {
flags[i][i] = true;
for j in (0..i) {
flags[j][i] = (b[j] == b[i] && (i-j < 3 || flags[j+1][i-1]));
if (flags[j][i] && i - j + 1 > max) {
start = j;
max = i - j + 1;
}
}
}
let end = start + max;
return (s[start as usize..end as usize]).to_string();
}
#[test]
fn test_longest_palindrome() {
let demo1 = String::from("abcda");
let ret = longest_palindrome(demo1);
assert_eq!(ret, "a");
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。