题目链接

  题目要求: 

  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 }
View Code

相关文章:

  • 2021-07-13
  • 2021-12-22
  • 2022-12-23
  • 2022-01-16
  • 2021-07-21
  • 2022-01-06
  • 2021-04-10
  • 2022-12-23
猜你喜欢
  • 2021-05-27
  • 2021-05-21
  • 2021-12-19
  • 2021-09-22
  • 2021-12-15
  • 2021-08-15
  • 2021-07-11
相关资源
相似解决方案