LeetCode 214 Shortest Palindrome (KMP)

 

Refer: https://segmentfault.com/a/1190000003059361

 

O(n^2) Solution

    public String shortestPalindrome(String s) {
        if(s == null || s.length() <= 1) return s;
        
        int len = s.length(); 
        int tail = len - 1;
        
        StringBuffer sb = new StringBuffer();
        while(tail >= 1) {
            if(isPan( s.substring(0, tail + 1) ) ) {
                sb = sb.append(s.substring(tail, s.length())).reverse();
                break;
            }
            tail--;
        }
        
        sb.append(s);
        
        return sb.toString();
    }
    
    private boolean isPan(String s) {
        if(s == null || s.length() <= 1) return true;
        
        int left = 0, right = s.length() - 1;
        while(left < right) {
            if(s.charAt(left) == s.charAt(right)) {
                left++;
                right--;
            } else return false;
        }
        
        return true;
    }

 

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