Sort and count


  • 0
    Q

    Use array sort firstly sort the String alphabetically, then loop the character array to find the count of even pairs character. Final result shall plus one if the count number is less than the length of the string.

    public int longestPalindrome(String s) {
            if (s == null) {
    			return 0;
    		}
    		char[] sArray = s.toCharArray();
    		Arrays.sort(sArray);
    		
    		int length = sArray.length;
    		
    		int count = 0;
    		int i = 0;
    		
    		while (i < length - 1) {
    			if (sArray[i] == sArray[i + 1]) {
    				count = count + 2;
    				i = i + 2;
    				continue;
    			} else {
    				i++;
    				continue;
    			}
    		}
    		
    		if (length > count) {
    			return count + 1;
    		} else {
    			return count;
    		}
        }

Log in to reply
 

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