• 214. Shortest Palindrome


    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"

    class Solution {
        public String shortestPalindrome(String s) {
            if(s == null || s.length() == 0) return s;
            int right = 1;
            for(int i = 2; i <= s.length(); i++){
                if(helper(s.substring(0, i))) right = i;
            }
            if(right == s.length()) return s;
            String front = s.substring(0, right);
            String back = s.substring(right);
            StringBuilder sb = new StringBuilder(back);
            String nback = sb.reverse().toString();
            return nback+front+back;
        }
        public boolean helper(String s){
            int left = 0, right = s.length() - 1;
            while(left < right){
                if(s.charAt(left) != s.charAt(right)) return false;
                left++;
                right--;
            }
            return true;
        }
    }

    1. brute force

    因为只能从front插入,所以先找从前往后最长palindrome,然后剩下的reverse后加到前面

    class Solution {
        public String shortestPalindrome(String s) {
            int i = 0, end = s.length() - 1, j = end; char chs[] = s.toCharArray();
            while(i < j) {
                 if (chs[i] == chs[j]) {
                     i++; j--;
                 } else { 
                     i = 0; end--; j = end;
                 }
            }
            return new StringBuilder(s.substring(end+1)).reverse().toString() + s;
        }
    }

    https://leetcode.com/problems/shortest-palindrome/discuss/60106/My-9-lines-three-pointers-Java-solution-with-explanation

  • 相关阅读:
    Java集合之LinkedHashMap
    ConcurrentHashMap原理分析
    Java集合之HashMap
    JAVA集合之ArrayList
    Python内建函数
    Vscode 安装Java Spring项目
    音频质量评估-2
    音频质量评估-1
    Python list 实现
    怎么测试大数据
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13171402.html
Copyright © 2020-2023  润新知