当前位置:网站首页>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 // 直接返回添加的字符加上原字符串即可
}
}
};
边栏推荐
- Roguelike游戏成破解重灾区,如何破局?
- Browser thread
- Double pointeur en langage C - - modèle classique
- The mysqlbinlog command uses
- Trying to use is on a network resource that is unavailable
- 有效提高软件产品质量,就找第三方软件测评机构
- Delay initialization and sealing classes
- 角色动画(Character Animation)的现状与趋势
- 同一局域网的手机和电脑相互访问,IIS设置
- Introduction to the differences between compiler options of GCC dynamic library FPIC and FPIC
猜你喜欢

PC easy to use essential software (used)

LeetCode:236. 二叉树的最近公共祖先

C語言雙指針——經典題型

egg. JS project deployment online server

ROS compilation calls the third-party dynamic library (xxx.so)

【嵌入式】使用JLINK RTT打印log

Screenshot in win10 system, win+prtsc save location

TP-LINK enterprise router PPTP configuration

Crash problem of Chrome browser

Sublime text using ctrl+b to run another program without closing other runs
随机推荐
查看局域网中电脑设备
What is the role of automated testing frameworks? Shanghai professional third-party software testing company Amway
生成器参数传入参数
Current situation and trend of character animation
可变长参数
C语言深度解剖——C语言关键字
Bottom up - physical layer
Revit secondary development Hof method calls transaction
704 binary search
深度剖析C语言数据在内存中的存储
TCP/IP协议
Function coritization
Shift Operators
MySQL learning record 07 index (simple understanding)
Hutool gracefully parses URL links and obtains parameters
Mobile phones and computers on the same LAN access each other, IIS settings
移位运算符
How to effectively conduct automated testing?
vb. Net changes with the window, scales the size of the control and maintains its relative position
win10系统中的截图,win+prtSc保存位置