My simple java solution accepted


  • -2
    S
    public class Solution {
        public String shortestPalindrome(String s) {
            
            
            char[] cs = s.toCharArray();
    		if(cs.length == 0)
    		{
    		    return "";
    		}
    		
    		if(cs.length == 1)
    		{
    		    return s;
    		}
    		
    		int startleft = (cs.length-1)/2;
    		int startright = startleft + (cs.length-1)%2;
    		String rtl = "";
    		while((rtl = shortestPalindrome(s, cs,startleft, startright))==null)
    		{
    			if(startleft == startright)
    			{
    				startleft--;
    			}
    			else
    			{
    				startright--;
    			}
    		}
    		
    		return rtl;
            
        }
        
        
    public static String shortestPalindrome(String s, char[] cs, int startleft, int startright)
    	{
    		
    		char[] sp = null;
    		int spstart = -1;
    		while(startright <cs.length)
    		{
    			if(startleft>-1)
    			{
    				if(cs[startleft] != cs[startright])
    				{
    					return null;
    				}
    			}
    			else
    			{
    				if(sp==null)
    				{
    					sp = new char[cs.length*2-1];
    					spstart = sp.length - cs.length;
    				}
    				sp[spstart+startleft]=cs[startright];
    			}
    			
    			startleft--;
    			startright++;
    			
    		}
    		
    		StringBuffer b = new StringBuffer();
    		if(startleft+1<0)
    		{
    			int offset = spstart+startleft+1;
    			int len = 0-(startleft+1);
    			return b.append(sp,offset,len).append(cs).toString();
    		}
    		else
    			return s;
    	}
    }``

Log in to reply
 

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