N^2 is time exceed????


  • 0
    T
     public String shortestPalindrome(String s) {
        int len=s.length();
        if(s==null||len==0)
          return " ";
        int i=0;
        int mark=0;
        int j=1;
        while(j<len){
            String temp=s.substring(i,j);
            if(isPalindrome(temp)){
                mark=j;
            }
            j++;
        }
         if(mark==len-1)
        	return s;
        StringBuffer sb=new StringBuffer();
        for(int k=len-1;k>=mark;k--){
            sb.append(s.charAt(k));
        }
        sb.append(s);
        return sb.toString();
    }
    public boolean isPalindrome(String s) {
    	if (s == null || s.length() == 0)
    		return true;
    	s = s.trim();
    	char[] num = s.toCharArray();
    	StringBuffer sb = new StringBuffer();
    	for (int i = 0; i < num.length; i++) {
    		char a = s.charAt(i);
    			sb.append(a);
    	}
    	String comp = sb.toString();
    	String res = sb.reverse().toString();
    	if (res.equals(comp))
    		return true;
    	else
    		return false;
    }

Log in to reply
 

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