资讯专栏INFORMATION COLUMN

[LeetCode] 214. Shortest Palindrome

liangdas / 1967人阅读

Problem

Given a string s, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.

Example 1:

Input: "aacecaaa"
Output: "aaacecaaa"
Example 2:

Input: "abcd"
Output: "dcbabcd"

Solution
class Solution {
    public String shortestPalindrome(String s) {
        int len = s.length();
        int i = len;
        for (i = len; i >= 0; i--) {
            if (isPalindrome(s.substring(0, i))) break;
        }
        StringBuilder sb = new StringBuilder();
        
        if (i < 0) {
            sb.append(s).reverse();
            return sb.toString()+s;
        }
        
        sb.append(s.substring(i)).reverse();
        return sb.toString() + s;
    }
    private boolean isPalindrome(String s) {
        int i = 0, j = s.length()-1;
        while (i <= j) {
            if (s.charAt(i++) != s.charAt(j--)) return false;
        }
        return true;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72590.html

相关文章

  • 214. Shortest Palindrome

    摘要:题目链接找到从头开始最长的那么只要把的加到前面就是结果了。找的过程可以用来做优化,由于,那么就照着里面见数组的方法来查,最后就是的长度,注意两个并在一起的要加分隔符,防止算的出问题。 214. Shortest Palindrome 题目链接:https://leetcode.com/problems... 找到string从头开始最长的palindrome substring:s[0...

    beita 评论0 收藏0
  • [Leetcode] Shortest Palindrome 最短回文拼接法

    摘要:第二个是,因为在第个位置,可以有最长为的相同前后缀,依次类推。匹配时分为几种情况字母相同,则和都加,且,因为后缀匹配的长度是前缀的长度加。注意为了方便处理空字符串,我们在反转拼接的时候中间加了,这个字符要保证不会出现在字符串中。 Shortest Palindrome Given a string S, you are allowed to convert it to a palin...

    Chiclaim 评论0 收藏0
  • Palindrome Pairs & Shortest Palindrome

    摘要:部分是回文的,在里面找是否有的。这里的范围是,最小是,因为要保证是两个单词,最大是,这时候要找出另一个和他相反的串。判断为回文,可以直接暴力,每个都判断一次。两个方向都找一遍就可能出现重复的情况,注意避免重复。例如,结果应该是。 Palindrome Pairs 链接:https://leetcode.com/problems... 这道题没想出来思路,参考了这个博客的内容:http:...

    CNZPH 评论0 收藏0
  • 前端 | 每天一个 LeetCode

    摘要:在线网站地址我的微信公众号完整题目列表从年月日起,每天更新一题,顺序从易到难,目前已更新个题。这是项目地址欢迎一起交流学习。 这篇文章记录我练习的 LeetCode 题目,语言 JavaScript。 在线网站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公众号: showImg(htt...

    张汉庆 评论0 收藏0
  • leetcode 部分解答索引(持续更新~)

    摘要:前言从开始写相关的博客到现在也蛮多篇了。而且当时也没有按顺序写现在翻起来觉得蛮乱的。可能大家看着也非常不方便。所以在这里做个索引嘻嘻。顺序整理更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新 前言 从开始写leetcode相关的博客到现在也蛮多篇了。而且当时也没有按顺序写~现在翻起来觉得蛮乱的。可能大家看着也非常不方便。所以在这里做个索引嘻嘻。 顺序整理 1~50 1...

    leo108 评论0 收藏0

发表评论

0条评论

liangdas

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<