题目要求:
Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.
For example:
Given "aacecaaa", return "aaacecaaa".
Given "abcd", return "dcbabcd".
这道题用暴力破解是无法通过LeetCode上的测试的。
1. 法一(暴力破解)
超过时间!!!!
1 int findCenter(string s) 2 { 3 int center = 0; 4 int szS = s.size(); 5 for (int i = 1; i < szS; i++) 6 { 7 int k = 1; 8 while (k <= i && k < szS - i) 9 { 10 if (s[i - k] != s[i + k]) 11 break; 12 k++; 13 } 14 if (i - k == -1 && i > center) 15 center = i; 16 } 17 return center; 18 } 19 20 string char2String(char c) 21 { 22 stringstream ss; 23 string s; 24 ss << c; 25 ss >> s; 26 return s; 27 } 28 29 string shortestPalindrome(string s) { 30 // clear spaces 31 if (s.front() == ' ') 32 s.erase(0, 1); 33 if (s.back() == ' ') 34 s.pop_back(); 35 36 string ret; 37 int szS = s.size(); 38 if (szS == 0) 39 ret = ""; 40 else if (szS == 1) 41 { 42 s += s; 43 ret = s; 44 } 45 else 46 { 47 ret = s; 48 int center = findCenter(s); 49 int left = center; 50 int right = center + left + 1; 51 if (szS - center - 1 > center && s[center] == s[center + 1]) 52 { 53 right = szS; 54 } 55 for (int i = right; i < szS; i++) 56 { 57 ret.insert(0, char2String(s[i])); 58 } 59 } 60 61 return ret; 62 }