214 Shortest Palindrome 最短回文串

给一个字符串 S, 你可以通过在字符串前面添加字符将其转换为回文串。找到并返回可以用这种方式转换的最短回文串。
例如:
给出 "aacecaaa",返回 "aaacecaaa"。
给出 "abcd",返回 "dcbabcd"。

详见:https://leetcode.com/problems/shortest-palindrome/description/

Java实现:

暴力解法:

class Solution {
    public String shortestPalindrome(String s) {
        if (s.isEmpty()) {
            return s;
        }
        int i = s.length() - 1;
        while (i >= 0) {
            String spre = s.substring(0, i + 1);
            if (isPalindrome(spre)) {
                break;
            }
            --i;
        }
        String pre = new StringBuilder(s.substring(i + 1)).reverse().toString();
        return pre + s;
    }

    private boolean isPalindrome(String s) {
        for (int i = 0, j = s.length() - 1; i < j; ++i, --j) {
            if (s.charAt(i) != s.charAt(j)) {
                return false;
            }
        }
        return true;
    }
}

 KMP算法解法:

class Solution {
    public String shortestPalindrome(String s) {
        if (s.isEmpty()) {
            return s;
        }
        String rs = new StringBuilder(s).reverse().toString();
        String newStr = s + "#" + rs;
        int[] next = new int[newStr.length()];
        for (int i = 1; i < newStr.length(); ++i) {
            int j = next[i - 1];
            while (j > 0 && newStr.charAt(i) != newStr.charAt(j)) {
                j = next[j - 1];
            }
            j += (newStr.charAt(i) == newStr.charAt(j)) ? 1 : 0;
            next[i] = j;
        }
        return rs.substring(0, s.length() - next[newStr.length() - 1]) + s;
    }
}

参考:https://www.cnblogs.com/ganganloveu/p/4621327.html

https://www.cnblogs.com/grandyang/p/4523624.html

https://leetcode.com/problems/shortest-palindrome/discuss/60141/C++-8-ms-KMP-based-O(n)-time-and-O(n)-memory-solution

posted on 2018-04-08 21:46  lina2014  阅读(283)  评论(0编辑  收藏  举报

导航