String rotateString(String s, int n) { int length = s.length; n = n % length; String sDouble = s + s; // 双重拼接 return sDouble.substring(n, n + length); }
String longestPalindrome(String s) { if (s.isEmpty) return"";
int start = 0, end = 0;
for (int i = 0; i < s.length; i++) { int len1 = expandAroundCenter(s, i, i); // 奇数长度回文 int len2 = expandAroundCenter(s, i, i + 1); // 偶数长度回文 int len = len1 > len2 ? len1 : len2;
if (len > end - start) { start = i - (len - 1) ~/ 2; end = i + len ~/ 2; } }
return s.substring(start, end + 1); }
// 辅助函数:从中心向两侧扩展,返回回文的长度 int expandAroundCenter(String s, int left, int right) { while (left >= 0 && right < s.length && s[left] == s[right]) { left--; right++; } return right - left - 1; }
// 测试代码 void main() { String s = "cbabcad"; print("Longest Palindromic Substring is: ${longestPalindrome(s)}"); }
// 单个字符一定是回文 for (int i = 0; i < n; i++) { dp[i][i] = true; }
// 检查长度为2的回文 for (int i = 0; i < n - 1; i++) { if (s[i] == s[i + 1]) { dp[i][i + 1] = true; start = i; maxLength = 2; } }
// 动态规划检查长度大于2的子串 for (int len = 3; len <= n; len++) { for (int i = 0; i < n - len + 1; i++) { int j = i + len - 1; if (s[i] == s[j] && dp[i + 1][j - 1]) { dp[i][j] = true; start = i; maxLength = len; } } }
return s.substring(start, start + maxLength); }
// 测试代码 void main() { String s = "cbabcad"; print("Longest Palindromic Substring is: ${longestPalindromeDP(s)}"); }