Java Easy Solution


  • 0
    Y
    public class Solution {
        private List<String> res = new ArrayList<>();
        HashMap<Character, Integer> M = new HashMap<>();
        
        public List<String> generatePalindromes(String s) {
            if (s == null || s.length() == 0) return res;
            
            for (char c : s.toCharArray()) {
                if (!M.containsKey(c)) {
                    M.put(c, 1);
                } else {
                    M.put(c, M.get(c)+1);
                }
            }
            
            boolean hasOdd = false;
            String begin = "";
            for (Map.Entry<Character, Integer> entry : M.entrySet()) {
                if (entry.getValue() % 2 != 0) {
                    if (!hasOdd) {
                        hasOdd = true;
                        M.put(entry.getKey(), entry.getValue()-1);
                        begin += entry.getKey();
                    } else {
                        return res;
                    }
                }
            }
            
            genPalin(s.length(), begin);
            
            return res;
        }
        
        private void genPalin(int len, String str) {
            if (str.length() == len) {
                res.add(new String(str));
            }
            
            for (Map.Entry<Character, Integer> entry : M.entrySet()) {
                if (entry.getValue() == 0) continue;
                M.put(entry.getKey(), entry.getValue()-2);
                genPalin(len, entry.getKey()+str+entry.getKey());
                M.put(entry.getKey(), entry.getValue()+2);
            }
            
        }
    }

Log in to reply
 

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