当前位置:网站首页>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 // 直接返回添加的字符加上原字符串即可
}
}
};
边栏推荐
- Delay initialization and sealing classes
- LeetCode:387. 字符串中的第一个唯一字符
- How to effectively conduct automated testing?
- On the inverse order problem of 01 knapsack problem in one-dimensional state
- Promise 在uniapp的简单使用
- vb. Net changes with the window, scales the size of the control and maintains its relative position
- Image, CV2 read the conversion and size resize change of numpy array of pictures
- Computer cleaning, deleted system files
- Swagger setting field required is mandatory
- Chrome浏览器的crash问题
猜你喜欢

被破解毁掉的国产游戏之光

pytorch训练好的模型在加载和保存过程中的问题

MySQL learning record 11jdbcstatement object, SQL injection problem and Preparedstatement object

sublime text的编写程序时的Tab和空格缩进问题

Roguelike game into crack the hardest hit areas, how to break the bureau?

swagger设置字段required必填

Visual implementation and inspection of visdom

704 binary search

LeetCode:124. 二叉树中的最大路径和

Precise query of tree tree
随机推荐
ESP8266-RTOS物联网开发
Bitwise logical operator
Analysis of the source code of cocos2d-x for mobile game security (mobile game reverse and protection)
Marathon envs project environment configuration (strengthen learning and imitate reference actions)
torch建立的网络模型使用torchviz显示
704 二分查找
Using pkgbuild:: find in R language_ Rtools check whether rtools is available and use sys The which function checks whether make exists, installs it if not, and binds R and rtools with the writelines
Function coritization
Purpose of computer F1-F12
【ROS】usb_ Cam camera calibration
Detailed explanation of heap sorting
704 binary search
Crash problem of Chrome browser
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
Navicat premium create MySQL create stored procedure
Current situation and trend of character animation
企微服务商平台收费接口对接教程
What are the common processes of software stress testing? Professional software test reports issued by companies to share
Cisp-pte practice explanation
marathon-envs项目环境配置(强化学习模仿参考动作)