My java solution


  • 0
    S

    I think this is my first solution to a Hard level problem :)

    My approach was to take out and store the characters from the back until the reminder of the string was a Palindrome, then simply return those stored characters plus the original string.

    public class Solution {
        public String shortestPalindrome(String s) {
            StringBuilder tail = new StringBuilder();
            String original = s;
            int index = s.length();
            if (s.length() < 2 || isPalindrome(s)) return s;  
            
            while (!isPalindrome(s.substring(0, index))){
                tail.append(s.charAt(index-1));
                index--;
            }
            
            return tail + original;
            
        }
        
        private boolean isPalindrome(String s){
            int len = s.length();
            
            int left;
            int right;
            
            if (len % 2 == 0){
                left = (len / 2) - 1;
                right = len / 2;
            } else{
                left = (len / 2) - 1;
                right = (len / 2) + 1;
            }
            
            while (left >= 0){
                if (s.charAt(left) != s.charAt(right)) return false;
                left--;
                right++;
            }
            
            return true;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.