当前位置:网站首页>LeetCode:214. Shortest palindrome string

LeetCode:214. Shortest palindrome string

2022-07-06 08:51:00 Bertil

Given a string s, You can convert a string to a palindrome string by adding characters in front of it . Find and return the shortest palindrome string that can be converted in this way .

Example 1:

 Input :s = "aacecaaa"
 Output :"aaacecaaa"

Example 2:

 Input :s = "abcd"
 Output :"dcbabcd"

Tips :

  • 0 <= s.length <= 5 * 10^4
  • s It's only made up of lowercase letters

### Their thinking 1. First invert the string s, Then traverse the original string , Judge whether the string is palindrome string according to whether the string is equal before and after inversion , So as to find the shortest palindrome string in the original string 2. Finally, directly return the added character plus the original string ( The added character is the string before the shortest palindrome string in the original string )

Code

/** * @param {string} s * @return {string} */
var shortestPalindrome = function(s) {
    
    const len = s.length
    if (len === 0) return ''
    //  Reverse string s
    let rev = s.split('').reduce((a, b) => b + a, '')
    for (let i = 0; i < len; i++) {
    
        //  Judge whether the string is palindrome string according to whether the string is equal before and after inversion 【rev.slice(i) Namely s.slice(0, len - i) Inverted string of 】
        if (s.slice(0, len - i) === rev.slice(i)) {
    
            //  If it is palindrome string , That is, the shortest palindrome string in the original string 
            return rev.slice(0, i) + s //  Directly return the added character plus the original string 
        }
    }
};
原网站

版权声明
本文为[Bertil]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060844309061.html