当前位置:网站首页>LeetCode:214. 最短回文串
LeetCode:214. 最短回文串
2022-07-06 08:44:00 【Bertil】
给定一个字符串 s,你可以通过在字符串前面添加字符将其转换为回文串。找到并返回可以用这种方式转换的最短回文串。
示例 1:
输入:s = "aacecaaa"
输出:"aaacecaaa"
示例 2:
输入:s = "abcd"
输出:"dcbabcd"
提示:
- 0 <= s.length <= 5 * 10^4
- s 仅由小写英文字母组成
### 解题思路 1.首先反转字符串s,然后遍历原字符串,根据字符串反转前后是否相等来判断字符串是不是回文字符串,从而找到原字符串中的最短回文字符串 2.最后直接返回添加的字符加上原字符串即可(添加的字符即原字符串中最短回文字符串之前的字符串)
代码
/** * @param {string} s * @return {string} */
var shortestPalindrome = function(s) {
const len = s.length
if (len === 0) return ''
// 反转字符串s
let rev = s.split('').reduce((a, b) => b + a, '')
for (let i = 0; i < len; i++) {
// 根据字符串反转前后是否相等来判断字符串是不是回文字符串【rev.slice(i)就是s.slice(0, len - i)的反转字符串】
if (s.slice(0, len - i) === rev.slice(i)) {
// 如果是回文字符串的话,即所求的原字符串中的最短回文字符串
return rev.slice(0, i) + s // 直接返回添加的字符加上原字符串即可
}
}
};
边栏推荐
- MySQL learning record 10getting started with JDBC
- 有效提高软件产品质量,就找第三方软件测评机构
- China polyether amine Market Forecast and investment strategy report (2022 Edition)
- JS pure function
- Esp8266-rtos IOT development
- egg. JS project deployment online server
- Cisp-pte practice explanation
- Generator parameters incoming parameters
- Unsupported operation exception
- Analysis of the source code of cocos2d-x for mobile game security (mobile game reverse and protection)
猜你喜欢
Target detection - pytorch uses mobilenet series (V1, V2, V3) to build yolov4 target detection platform
Guangzhou will promote the construction of a child friendly city, and will explore the establishment of a safe area 200 meters around the school
JVM performance tuning and practical basic theory - Part 1
Double pointeur en langage C - - modèle classique
Analysis of the source code of cocos2d-x for mobile game security (mobile game reverse and protection)
Image, CV2 read the conversion and size resize change of numpy array of pictures
[MySQL] lock
Sublime text in CONDA environment plt Show cannot pop up the problem of displaying pictures
Navicat premium create MySQL create stored procedure
pcd转ply后在meshlab无法打开,提示 Error details: Unespected eof
随机推荐
R language uses the principal function of psych package to perform principal component analysis on the specified data set. PCA performs data dimensionality reduction (input as correlation matrix), cus
Restful API design specification
swagger设置字段required必填
LeetCode:剑指 Offer 03. 数组中重复的数字
vb.net 随窗口改变,缩放控件大小以及保持相对位置
China high purity silver nitrate Market Research and investment strategy report (2022 Edition)
Detailed explanation of heap sorting
Generator parameters incoming parameters
Shift Operators
Chrome浏览器的crash问题
[NVIDIA development board] FAQ (updated from time to time)
LeetCode:221. 最大正方形
有效提高软件产品质量,就找第三方软件测评机构
Current situation and trend of character animation
Unsupported operation exception
如何有效地进行自动化测试?
延迟初始化和密封类
Unified ordering background interface product description Chinese garbled
UnsupportedOperationException异常
Marathon envs project environment configuration (strengthen learning and imitate reference actions)