标签:动态规划 面试题 leetcode algorithm
给定个字符串,返回串中包含的最长的回文串。
string longestPalindrome(string s) { if(s.size() <= 1) return s; //vector<vector<bool> >dp(s.size(),vector<bool>(s.size(), false)); bool dp[1000][1000] = {false}; //bool **dp = new bool[s.size()][s.size()]; int Len = s.size(); int longest = 0; int start = 0; //init dp[i,i] = true for (int i = 0; i < Len; ++i) dp[i][i] = true; //init dp[i, i + 1] for (int i = 0; i < Len - 1; ++i) if(s[i] == s[i + 1]) { dp[i][i + 1] = true; longest = 2; start = i; } for (int i = Len - 3; i >= 0; --i) for(int j = i + 2; j < Len; ++j) { if(dp[i + 1][j - 1] && s[i] == s[j]) { dp[i][j] = true; if(longest < j - i + 1) { longest = j - i + 1; start = i; } } } return s.substr(start,longest); }
【leetcode】Longest Palindromic Substring,布布扣,bubuko.com
【leetcode】Longest Palindromic Substring
标签:动态规划 面试题 leetcode algorithm
原文地址:http://blog.csdn.net/shiquxinkong/article/details/27592233