Java Arrays.sort (beat 66%)


  • 1
    public int longestPalindrome(String s) {
    	char[] chr = s.toCharArray();
    	if (chr.length<2){
    		return chr.length;
    	}
    	boolean single = false;
    	int count = 0;
    	
    	Arrays.sort(chr);
    	for(int i=0; i<chr.length; ){
    		if(i<chr.length-1 && chr[i]==chr[i+1]){
    			count +=2;
    			i +=2;
    		}else{
    			i ++;
    			single = true;
    		}
    	}
    	if(single==true){count++;}
    	return count;
    }

  • 1

    The idea is: first sort the char[], then count how many doubles are there,
    If there are singles, plus one.


Log in to reply
 

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