当前位置:网站首页>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 // 直接返回添加的字符加上原字符串即可
}
}
};
边栏推荐
- Shift Operators
- The problem and possible causes of the robot's instantaneous return to the origin of the world coordinate during rviz simulation
- egg. JS directory structure
- poi追加写EXCEL文件
- How to conduct interface test? What are the precautions? Nanny level interpretation
- ESP8266-RTOS物联网开发
- Guangzhou will promote the construction of a child friendly city, and will explore the establishment of a safe area 200 meters around the school
- MySQL learning record 11jdbcstatement object, SQL injection problem and Preparedstatement object
- Research and investment forecast report of citronellol industry in China (2022 Edition)
- 角色动画(Character Animation)的现状与趋势
猜你喜欢
After PCD is converted to ply, it cannot be opened in meshlab, prompting error details: ignored EOF
Double pointeur en langage C - - modèle classique
[embedded] print log using JLINK RTT
win10系统中的截图,win+prtSc保存位置
[brush questions] top101 must be brushed in the interview of niuke.com
JS native implementation shuttle box
C语言双指针——经典题型
同一局域网的手机和电脑相互访问,IIS设置
C语言深度解剖——C语言关键字
深度剖析C语言数据在内存中的存储
随机推荐
What is the role of automated testing frameworks? Shanghai professional third-party software testing company Amway
The harm of game unpacking and the importance of resource encryption
【嵌入式】Cortex M4F DSP库
hutool优雅解析URL链接并获取参数
MySQL learning records 12jdbc operation transactions
Chrome浏览器的crash问题
Computer cleaning, deleted system files
Revit 二次开发 HOF 方式调用transaction
按位逻辑运算符
[MySQL] lock
生成器参数传入参数
The problem and possible causes of the robot's instantaneous return to the origin of the world coordinate during rviz simulation
Crash problem of Chrome browser
广州推进儿童友好城市建设,将探索学校周边200米设安全区域
目标检测——Pytorch 利用mobilenet系列(v1,v2,v3)搭建yolov4目标检测平台
On the inverse order problem of 01 knapsack problem in one-dimensional state
Visual implementation and inspection of visdom
【Nvidia开发板】常见问题集 (不定时更新)
Screenshot in win10 system, win+prtsc save location
Image, CV2 read the conversion and size resize change of numpy array of pictures