solution.md 1.7 KB
Newer Older
ToTensor's avatar
ToTensor 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
# 最短回文串

<p>给定一个字符串 <em><strong>s</strong></em>,你可以通过在字符串前面添加字符将其转换为回文串。找到并返回可以用这种方式转换的最短回文串。</p>

<p> </p>

<p><strong>示例 1:</strong></p>

<pre>
<strong>输入:</strong>s = "aacecaaa"
<strong>输出:</strong>"aaacecaaa"
</pre>

<p><strong>示例 2:</strong></p>

<pre>
<strong>输入:</strong>s = "abcd"
<strong>输出:</strong>"dcbabcd"
</pre>

<p> </p>

<p><strong>提示:</strong></p>

<ul>
	<li><code>0 <= s.length <= 5 * 10<sup>4</sup></code></li>
	<li><code>s</code> 仅由小写英文字母组成</li>
</ul>


## template

```cpp
#include <bits/stdc++.h>
using namespace std;

class Solution
{
public:
    string shortestPalindrome(string s)
    {

        string rev(s);
        reverse(rev.begin(), rev.end());
        ;
        string combine = s + "#" + rev;

        vector<int> lps(combine.length(), 0);
        int remove = getLPS(combine, lps);

        string prepend = rev.substr(0, rev.length() - remove);
        return prepend + s;
    }

    int getLPS(string s, vector<int> &lps)
    {

        int j = 0, i = 1;

        while (i < s.length())
        {

            if (s[i] == s[j])
            {
                lps[i] = j + 1;
                i++;
                j++;
            }
            else
            {

                if (j != 0)
                {
                    j = lps[j - 1];
                }
                else
                {
                    lps[i] = 0;
                    i++;
                }
            }
        }
        return lps[lps.size() - 1];
    }
};


```

## 答案

```cpp

```

## 选项

### A

```cpp

```

### B

```cpp

```

### C

```cpp

```