Shortest Palindrome

https://www.lintcode.com/problem/shortest-palindrome/description

public class Solution {
    /**
     * @param str: String
     * @return: String
     */
    public String convertPalindrome(String str) {
        // Write your code here
        StringBuilder stringBuilder = new StringBuilder(str);
        int index = 0;
        while (true) {
            if (isFit(stringBuilder)) {
                return stringBuilder.toString();
            }
            stringBuilder.insert(index, stringBuilder.charAt(stringBuilder.length() - 1 - index));
            index++;
        }
    }

    private boolean isFit(StringBuilder temp) {
        int start = 0;
        int end = temp.length() - 1;
        while (start < end) {
            if (temp.charAt(start) == temp.charAt(end)) {
            } else {
                return false;
            }
            start++;
            end--;
        }
        return true;
    }
}

你可能感兴趣的:(Shortest Palindrome)