Solution using sort and stack


  • 0
    R

    Simple Java solution with sort(O(nlongn)) and stack.

    public class Solution {
        public int longestPalindrome(String s) {
            char[] chs = s.toCharArray();
            int sum = 0;
            Arrays.sort(chs);
            Stack stk = new Stack();
            for(int i = 0; i<chs.length; i++){
                if(!stk.empty() && stk.peek().equals(chs[i])){
                    stk.pop();
                    sum+=2;
                }else{
                    stk.push(chs[i]);
                }
            }
            if(stk.empty()){
                return sum;
            }
            return sum+1;
        }
    }
    

Log in to reply
 

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